I'm making a program/game that needs to convert a string input (mathematical function, ex. sin(x)+2).
Looking around I found the function eval, which converts string to function. This found to be exsistent in lua aswell named loadstring.
Although trying to run code, it doesn't convert string to math properly.
f = "sin(4)"
love.window.setTitle(loadstring("return " .. f)) -- put a () after f) to actually call the loaded string
though not if you want to set it every frame... that would probably be "slow as hell".
Last edited by zorg on Fri Nov 21, 2014 5:27 am, edited 1 time in total.
Me and my stuff True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
userinput = "math.sin(4); return 'a'"
func = loadstring(userinput)
ok,msg = pcall(func) --This call func, and returns true if there was no error or false if there was
if ok then --The code ran fine
if msg then
print(msg) --Prints "a"
end
else --Oops it crashed
print(msg) --ERROR Bla bla bla
end
You dont want the user to execute dangerous code, for example if the user inputs:
env = {math = math, string = string}
userinput = "love = {graphics = "a"}"
func = loadstring(userinput)
ok,msg = pcall(func)
print(love.graphics)--table 0x....
if ok then
if msg then
print(env.love.graphics) --Prints "a"
end
else
print(msg)
end
NOTE: If you want the user to use a function you have, then you should put it in the environment as I did above with math and string but this could be dangerous too, since you are just referencing a table, then if the user did this
math.floor wont do what you expect it to do, to allow the user to use math.floor while not allowing to change the behavior of YOURS math.floor you have to deep copy the math table
Haha, you're right, i did forgot the (), my bad! Though you did make a minor typographical mistake: wrote "loadsting" instead of loadstring in one of your code blocks.
Me and my stuff True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.