Page 1 of 1

please help for dynamic variable name

Posted: Sat Dec 28, 2013 6:53 pm
by Pandafox
hi,

sorry because probably my question is easy to resolve... but I didn't used LUA for a long time...

I can't activate or deactivate a lightsource using the "dynamic name" of it, and I can't remember how to...?
this is the script :

Code: Select all

function removetorchlight(self)
	print("remove light")
	local name_of_the_light = string.format("%s%u","torch_auto_light",self.id:sub(14,string.len(self.id)))
	print(name_of_the_light)
	name_of_the_light:deactivate()
end
the " print(name_of_the_light) " write the good string of the id of the light but it don't works with the deactivate function.
error : attempt to call method 'deactivate' (a nil value) X

please help me :roll:

Re: please help for dynamic variable name

Posted: Sat Dec 28, 2013 7:23 pm
by JohnWordsworth
If you have an entity in your world called "door_blue" say, then you can access the entity directly by using something like the following: door_blue:open(). As there is no variable called door_blue in the local scope it goes off and looks for an entity in the dungeon with the same name - which works and everyone is happy.

The problem with the example you have posted is that you are storing the ID of an entity in a local variable. So, when you print the variable it shows the correct entity name, but when you do this...

name_of_the_light:deactivate();

What you are actually trying to do is call the method 'deactivate' on the string object called name_of_the_light. Luckily, there is a handy method to get a reference to the entity itself from the name, so you can do the following...

Code: Select all

local light_entity = findEntity(name_of_the_light);
light_entity:deactivate();
And this allows you to call deactivate on the object itself. A good idea is to make sure that the entity is actually found - because if no entity is found the above example will crash! This version is safer...

Code: Select all

local light_entity = findEntity(name_of_the_light);

if ( light_entity ~= nil ) then
    light_entity:deactivate();
end
Hope this helps!

Re: please help for dynamic variable name

Posted: Sat Dec 28, 2013 7:44 pm
by Pandafox
ahhh !!! yes ! I understand !

thanks a lot for your help :)