Alternative to Python's eval in Lua

I want to solve an equation, the equation is given to me in a string.

In Python, I could simply do:

print(eval("12+23"))    # prints 35 as intended

In Lua, we have loadstring, but it does not work.

print(loadstring("12+23"))    -- nil [string "12+23"]:1: Expected identifier when parsing expression, got '12'

Is there a workaround, or do I have to write the function myself?

2 Likes

what are you trying to do in this instance?

Solve a math problem, which is given to me in a string.

could you do the math problem then make it a string?
you can also just print
12+23 i think

print(12+23) i think would work

No, I said, the math problem is given to me in a string. I don’t know the numbers that were used to create the problem.

No. As I said, I am given a string.

oh, do you know the operator?
if you do it will make it 100x easier

No, I do not know anything about the math problem except its final string.
Also, they can have more than 1 operator. For example, "12+23-(5*7)"

Make sure you return the result:

local result = loadstring("return 12+23")()
print(result)

It returns a function, just call it like above ^

It returns function: <random hex gibberish>

is this like a calculator? cause im wondering now

Thanks. Kinda weird that Python and Lua have this thing different.

No, it is a math problem generator. First, it generates a string of random operations, then I have to get the answer.

well its luau, which is kinda weird tbh

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.