Lua tables help

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
Bindie
Party member
Posts: 151
Joined: Fri Jan 23, 2015 1:29 pm

Lua tables help

Post by Bindie »

Hey, if I got a table like:

Code: Select all

Map[1] = {x=0,y=1, variables = {1,2,3}}
and then for some reason I want to add lots of variables:

Code: Select all

Map[1].tile = 24
Map[1].AnimTable = {}
Map[1].Treasure = 42
But I want a more effective way, not including Map[1] in every line.

Is there a syntax?
Muris
Party member
Posts: 131
Joined: Fri May 23, 2014 9:18 am

Re: Lua tables help

Post by Muris »

Bindie wrote: snip
Assuming you cannot set the values during the creation of map[1] such as:

Code: Select all

Map[1] = 
{
  x=0,
  y=1, 
  variables = {1,2,3},
  tile = 24,
  AnimTable = {},
  Treasure = 42
}
You could create local variable and set it to point same table

Code: Select all

local a = Map[1]
a.tile = 24
a.AnimTable = {}
a.Treasure = 42
If you want to add them into every single table inside Map, then

Code: Select all

for i,v in pairs( Map )
  if type( v ) == "table" then
    v.tile = 24
    v.AnimTable = {}
    v.Treasure = 42
  end
end
If you need to add them into every single subtable of a subtable in Map, you'd need to use recursion or probably coroutines, which could be done with something along the lines of:

Code: Select all

local Map = { 
  [1] = {},
  [2] = { [1] = {} }
}

local function iterateTable( t, func ) 
  if type(t) == "table" then
	  for i,v in pairs(t) do
  	  iterateTable( v, func )
  	end
 	  func(t)
  end
end

iterateTable( Map, function(t) 
    t.tile = 24
    t.AnimTable = {}
    t.Treasure = 42
	end )
Bindie
Party member
Posts: 151
Joined: Fri Jan 23, 2015 1:29 pm

Re: Lua tables help

Post by Bindie »

Awesome. Thanks.
User avatar
kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Location: Madrid, Spain
Contact:

Re: Lua tables help

Post by kikito »

This is the shortest one without adding a new function:

Code: Select all

local m = Map[1]
m.tile = 24
m.AnimTable = {}
m.Treasure = 42
EDIT: Apparently I was ninja'd by an answer and a "thank you" post. This looked empty when I pressed "submit", I swear.
When I write def I mean function.
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 4 guests