How to use variables within variables? help?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
gen424
Prole
Posts: 1
Joined: Wed Jun 12, 2013 5:49 am

How to use variables within variables? help?

Post 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
User avatar
micha
Inner party member
Posts: 1083
Joined: Wed Sep 26, 2012 5:13 pm

Re: How to use variables within variables? help?

Post 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.
Post Reply

Who is online

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