Page 1 of 1
Lua tables help
Posted: Wed Jan 28, 2015 8:23 pm
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?
Re: Lua tables help
Posted: Wed Jan 28, 2015 9:18 pm
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 )
Re: Lua tables help
Posted: Fri Jan 30, 2015 4:07 pm
by Bindie
Awesome. Thanks.
Re: Lua tables help
Posted: Mon Feb 02, 2015 9:58 pm
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.