182 posts
Posted 07 April 2013 - 06:43 PM
Hello,
I need to set a global variable via a function. I have tried:
function set(var, val)
if type(val) == "string" then
_G[tostring(var)] = tostring(val)
end
end
variable = "1st"
print(variable) -- prints 1st
set(variable, "2nd")
print(variable) -- prints 1st
How can I do so?
182 posts
Posted 07 April 2013 - 06:55 PM
I have also tried loadstring too.
1688 posts
Location
'MURICA
Posted 07 April 2013 - 07:57 PM
For what purpose do you need to do this? It seems like there's a better way to accomplish what you're going for.
182 posts
Posted 07 April 2013 - 08:05 PM
I have been messing around with metatable and would like to move forward but to so I need to be able to do this.
182 posts
Posted 09 April 2013 - 02:28 AM
Can I get a bump?
620 posts
Location
Holland
Posted 09 April 2013 - 02:34 AM
Tostring(var) gets the contents of var not the name you just got to pass the variable name as a string and you'll be good
199 posts
Location
Switzerland
Posted 09 April 2013 - 03:10 AM
This should work.
simply use ur function to declare the variable from the beginning on.
function set(var, val)
if type(val) == "string" then
_G[var] = val -- as axander mentioned already var does not need to have tostring cause you already pass the name as string. the tostring for val is useless to cause you already make sure it is a string with the if clause.
end
end
set("variable", "Moep")
print(variable)
set("variable", "Meep")
print(variable)
at all i dont understand why you need a function for this.
Just use variable = "whatever" without local
does the same