Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to table in lua [duplicate]

I am newbie in lua. I need to convert following string to lua table. How could I do this?

str = "{a=1, b=2, c={d=3,e=4} }"

I want to convert this string to lua table, so that I can access it like this:

print(str['a']) -- Output : 1
print(str['c']['d']) -- Output : 3
like image 318
akashdeep Avatar asked Oct 17 '25 06:10

akashdeep


1 Answers

You could simply add a str = to the beginning of the string and let the interpreter load that string as a chunk for you. Note that loadstring doesn't run the chunk but returns a function. So you add () to call that function right away and actually execute the code:

loadstring("str = "..str)()

This would do the same thing:

str = loadstring("return "..str)()

If you don't generate the string yourself, that can be dangerous though (because any code would be executed). In that case, you might want to parse the string manually, to make sure that it's actually a table and contains no bad function calls.

like image 58
Martin Ender Avatar answered Oct 20 '25 05:10

Martin Ender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!