Help with your scripting

How to Randomise a Lua Table

How to Randomise a Lua Table

Postby Shando » 17 Mar 2018, 00:55

Hi All,

I saw a comment by Karma over on Discord about randomly turning off/on lights in a scene at Dusk/Dawn and thought that it would be pretty easy if you set up a Lua table containing all of the Light IDs, randomised the table and then just looped through it turning off (or on) each light. You could even have separate tables for each "district" in the city (N, NE, E, SE, S, SW, W, NW and CBD for example).

So, here is a script showing how to randomise a Lua table:
Code: Select all
-- Function to Randomise a Lua Table
--      inTbl = Table to be Randomised
function randomiseTable ( inTbl )
   -- Get the length of the Table
   local nT = tableLength ( inTbl )

   -- Loop BACKWARDS through the Table
   while nT > 2 do
      -- Get a Random Table Entry
      local iRand = math.random ( nT )

      -- Swap the Current Table Entry (nT) with the Random one (iRand)
      inTbl[nT], inTbl[iRand] = inTbl[iRand], inTbl[nT]

      -- Move to the next (i.e. previous) Table Entry
      nT = nT - 1

   -- Return the Randomised Table
   return inTbl

-- Function to get the Length of a Table
--      inT = Table whose Length is required
function tableLength ( inT )
   -- Initialise a Counter
   local iC = 0

   -- Loop through the Table
   for _ in pairs ( inT ) do
      -- Increment the Counter for each Table Entry
      iC = iC + 1

   -- Return the Counter
   return iC

Hope this is helpful.



PS: I didn't write the randomise code, but I can't remember where I got it from (probably the main Lua site?)
Alienware 17 (i7-4700MQ 2.4GHz 16GB GTX770M Win 10 64)

Love, Hope, Strength
User avatar
Skyline Moderator
Skyline Moderator
Posts: 484
Joined: 06 Mar 2013, 22:35
Location: Kings Beach, Queensland
Skill: Programmer
Skill: Scripter
Skill: Level Designer

Re: How to Randomise a Lua Table

Postby SolarPortal » 17 Mar 2018, 13:33

Thanks for sharing Shando :) It may be wise to post the link of this topic on discord, so others can see it :)
Conceive, Quantify & Do!
Skyline Game Engine - Lead Developer.
Please provide as much information as possible when asking for help.

Specs: OS: Win 10 64bit, CPU: Intel i7 3770 3.4ghz x 4 core(8 threads), GPU: Nvidia GTX 1060 6GB, Ram: 16gig DDR3, Windows on 250gb Samsung Evo 860
User avatar
Skyline Founder
Skyline Founder
Posts: 3134
Joined: 29 Jul 2012, 15:56
Location: UK
Skill: 3D Modeller
Skill: 2D Artist
Skill: Programmer
Skill: Level Designer

Return to Lua Scripting

Who is online

Users browsing this forum: No registered users and 2 guests