Loadstring, how to use?

Asked

Viewed 882 times

2

I’m using the loadstring function, but I don’t know if this is the right way:

a= "st = {b=1, c=2}"
st = {}
b = loadstring(a)
b()
print(st.b)

Is there any simpler way?

  • It depends on what you call the simplest. If I understood, it doesn’t exist. Why would there be?

  • More simply I meant less polluted. I did so: st = "{b=1, c=2}" st = "st=".. st st loadstring(st) print(st.b)

  • In such artificial examples, it is complicated to say what can be less polluted. For example print(1) produces the same result in this case and is less polluted. You can do intermediate things but it’s a matter of taste since this is not a real problem.

  • Yes, but the most practical way to use the Loadstring, which is?

1 answer

3


If you don’t need to create the global variable st, use

b = loadstring("return {b=1, c=2}")()

If you want to do this often, consider something like

function eval(x)
  return loadstring("return "..x)()
end
  • Ah, the great magic is Return. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.