function setup()
obj0=456
obj1=9899
obj2=5453
obj3=54
obj5=3232
obj6=232
obj7="hello"
obj8=889
target=1
end
function draw()
--//when user input "target" detected//--
if target==0 then
print(obj0)
elseif target==1 then
print(obj1)
elseif target==2 then
print(obj2)
elseif target==3 then
print(obj3)
elseif target==4 then
print(obj4)
elseif target==5 then
print(obj5)
elseif target==6 then
print(obj6)
elseif target==7 then
print(obj7)
elseif target==8 then
print(obj8)
end
end
Now there are only 8 objs,but if I add to 50,I can’t imagine how many “elseif” I have to use.Is there any thing like"obj.target" in lua? Thanks!
function setup()
objects = {}
target = 1
-- Add your objects
addObject( 456 )
addObject( 9899 )
addObject( "hello" )
addObject( 123 )
-- ... and so on
end
function addObject( value )
table.insert( objects, value )
end
function draw()
-- when user input "target" detected
print( objects[target] )
end
If you have not read it, I recommend the online manual for Lua version 5.0 and its advice on constructing new tables. A variation on @Simeon’s advice would be:
function setup()
obj = {
[0] = 456, -- If you really want the first obj to be 'obj[0]'
9899,
5453,
54,
3232,
232,
"hello",
889
}
target = 1
end
function draw()
print(obj[target]) -- But generally not a good idea to have 'print()' called
-- up to 60 times a second
end