Page 1 of 1

How to use variables within variables? help?

Posted: Wed Jun 12, 2013 7:25 am
by gen424
Error Object.lua:21 attempt to index global '_g' (a nil value) stack
traceback: Object.lua:21: in function 'draw'
main.lua:24: in function 'draw' [string "boot.lua"]:410: in function <[string "boot.lua"]:373> [C]: in function 'xpcall'

how to fix? was trying to call a variable within a function name but dont know how... help?

Code: Select all

object = {}
object.list = {}
objectamount = 2
object.requireList = {
	--make sure to change the for loop in the object.require function.
	[1] = "test1",
	[2] = "test2"
}

function object.require()
--for the number of objects in "object.require_list", address each object handler with it's respective ids and call them with the "require()" function.
	print(object.requireList[1] .. ".draw")
	for i=1, objectamount, 1 do
		require(object.requireList[i]) 
		print("Loaded " .. object.requireList[i])
	end
end

function object.draw()
	for i=1, objectamount, 1 do
		_g[object.requireList[i] .. ".draw"]()
	end
end

Re: How to use variables within variables? help?

Posted: Wed Jun 12, 2013 8:48 am
by micha
The global scope is called _G with a capital G.

It looks like you have a table with strings that contain the names of function or objects. If you can, you should put the objects directly into the table. That way you can do this (without the _G-construction):

Code: Select all

for k in pairs(object) do
  k.draw()
end
This, however, only works, if all the objects already exist, when you set up the table.