Log in to vote

Question with loadstring(String)

Asked by 8 years ago

I was trying to do tests on creating equations in string forms and using them to calculate numbers. It is supposed to print "10", but it is printing "nil".

local E = "X+Y" local X = 9 local Y = 1 local A = 0

A = loadstring(E) print(A)

Do I have something not working/missing to solve the equation?

1 answer

Log in to vote
Answered by
MrNicNac 855 Moderation Voter
8 years ago

Your code needs to look like this:

local E = "X+Y" 
X = 9 
Y = 1

A = loadstring("return " .. E)() print(A)

First off, you need to call the function returned by loadstring with () at the end of loadstring(String). Second, you need to return E as I have shown.

Also, the variables will not carry over to the loadstring function unless you make them global (not _G). My example prints 10.

That works. Thanks. Ill be able to use it on a larger scale soon. :) FromLegoUniverse 264 — 8y

Answer this question