please help for dynamic variable name

Talk about creating Grimrock 1 levels and mods here. Warning: forum contains spoilers!
Post Reply
User avatar
Pandafox
Posts: 268
Joined: Wed Apr 11, 2012 11:25 pm
Location: France
Contact:

please help for dynamic variable name

Post 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:
User avatar
JohnWordsworth
Posts: 1397
Joined: Fri Sep 14, 2012 4:19 pm
Location: Devon, United Kingdom
Contact:

Re: please help for dynamic variable name

Post 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!
My Grimrock Projects Page with links to the Grimrock Model Toolkit, GrimFBX, Atlas Toolkit, QuickBar, NoteBook and the Oriental Weapons Pack.
User avatar
Pandafox
Posts: 268
Joined: Wed Apr 11, 2012 11:25 pm
Location: France
Contact:

Re: please help for dynamic variable name

Post by Pandafox »

ahhh !!! yes ! I understand !

thanks a lot for your help :)
Post Reply