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

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Frightening man
Prole
Posts: 2
Joined: Fri Oct 23, 2020 2:21 am

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

Post 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!
User avatar
steVeRoll
Party member
Posts: 131
Joined: Sun Feb 14, 2016 1:13 pm

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

Post 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?
User avatar
radgeRayden
Prole
Posts: 29
Joined: Sun Jul 27, 2014 6:49 pm
Location: Brasil
Contact:

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

Post 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.
Frightening man
Prole
Posts: 2
Joined: Fri Oct 23, 2020 2:21 am

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

Post by Frightening man »

Thank you both, loadstring did the trick.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 82 guests