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
   end

   -- Return the Randomised Table
   return inTbl
end

-- 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
   end

   -- Return the Counter
   return iC
end


Hope this is helpful.

Regards

Shando

PS: I didn't write the randomise code, but I can't remember where I got it from (probably the main Lua site?)
Ryzen 7 4800H 16GB GTX1650 Win 11 64
Love, Hope, Strength http://www.lovehopestrength.co.uk
User avatar
Shando
Skyline Moderator
Skyline Moderator
 
Posts: 560
Joined: 06 Mar 2013, 22:35
Location: Moffat 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 :)
Skyline Game Engine - Lead Dev.
Please provide as much info as possible when asking for help.


Specs: OS: Win 10 64bit, CPU: Intel i7 4770 3.4ghz x 4 core(8 threads), GPU: Nvidia GTX 1060 6GB, Ram: 16gig DDR3, Windows on 250gb Samsung Evo 860

Twitter: @SolarPortal
Instagram: @SolarPortal
User avatar
SolarPortal
Skyline Founder
Skyline Founder
 
Posts: 3631
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 6 guests

cron