This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Imque's profile picture

[Lua] Set Variable via Function

Started by Imque, 07 April 2013 - 04:43 PM
Imque #1
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?
Imque #2
Posted 07 April 2013 - 06:55 PM
I have also tried loadstring too.
Kingdaro #3
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.
Imque #4
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.
Imque #5
Posted 09 April 2013 - 02:28 AM
Can I get a bump?
superaxander #6
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
LordIkol #7
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