Page 1 of 1

Using a string with variables such as string = "5a+9b"

Posted: Fri Oct 23, 2020 2:34 am
by Frightening man
I cant seem to find a way to convert a string including
-numbers
-mathematical symbols (such as '+')
-variables.

Is there any way to do this?
To be clear, I want something like

Code: Select all

  local a = 2
  MyString = "5a+10"
  local b = MyString+5     --b=25
to work.
First post, very noob.
Thanks for your help!

Re: Using a string with variables such as string = "5a+9b"

Posted: Fri Oct 23, 2020 10:37 am
by steVeRoll
Yes, this is possible using Lua's loadstring function, although it would require a bit more work with function environments and such...
What exactly do you want to achieve with this?

Re: Using a string with variables such as string = "5a+9b"

Posted: Fri Oct 23, 2020 10:38 am
by radgeRayden
Welcome to the forums. There is no feature in lua to evaluate expressions with that notation. If you really want to use this string as is, you would have to parse it. If you're allowed to change the notation, you could write it as standard lua, eg. `"5*a+10"`, and use `loadstring` to evaluate it into a function. `setfenv` would then be able to insert `a` into the function environment and you would be able to calculate the result.

Re: Using a string with variables such as string = "5a+9b"

Posted: Mon Oct 26, 2020 1:24 am
by Frightening man
Thank you both, loadstring did the trick.