• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community
  • The forum is currently open to new registrations. The registration will close for a short period of time when reaching 500 active members, to upgrade the server resources.

How to loadstring()? (1 Viewer)

Hikooshi

Newcomer
Joined
Apr 4, 2021
Messages
2
Reaction score
0
Code:
local a = 1
loadstring("b=a+1 print(b)")

This code doesn't work. Error - a is nil. But if a is global then code works. How to use this function with local a? Lua 5.1
 

GavinW

Newcomer
Creator of RiscLua
Joined
Oct 21, 2020
Messages
40
Reaction score
17
Age
82
Location
UK
Website
www.wra1th.plus.com
You cannot. In Lua 5.2 loadstring is replaced by load which can take an environment as its fourth argument, but that will not help you with using a local variable.
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
45
Reaction score
31
Location
Italy
Website
github.com
You can, however, use loadstring to define functions that accept arguments, and pass the local variable as argument. For example:

Code:
local a = 1
loadstring("return function(a) local b=a+1 print(b) end")( )(a)
 

Hikooshi

Newcomer
Joined
Apr 4, 2021
Messages
2
Reaction score
0
You can, however, use loadstring to define functions that accept arguments, and pass the local variable as argument. For example:

Code:
local a = 1
loadstring("return function(a) local b=a+1 print(b) end")( )(a)
Yes, this works, but what is the third bracets "(a)"?
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
45
Reaction score
31
Location
Italy
Website
github.com
The third bracket is for passing the argument. I'll break it down into individual steps, so to make it (hopefully) clearer:

Code:
local a = 1
local f = loadstring("return function(x) local b=x+1 print(b) end") -- step 1
local g = f( ) -- step 2
g(a) -- step 3

At step 1, loadstr returns a function whose body is the string it receives as argument. In this case this is equivalent to writing:

Code:
local function f( ) return function(x) local b=x+1 print(b) end

Note that loadstring just returns a function, but it doesn't execute it. This function (f), when executed (step 2), returns another function that accepts an argument. Here I called it 'x' instead of 'a' to make clear that it is the argument, not (yet) the local variable 'a'. Step 2 thus ends up being equivalent to writing:

Code:
local function g(x) local b=x+1 print(b) end

Finally, at step 3 we execute the function g passing it 'a' as argument (thus x=a).

The original example is obtained by merging the three steps into one.

BTW, you can do it in another way which is arguably simpler, but I don't know if it works in Lua 5.1:

Code:
local a = 1
loadstring("local a=({...})[1] local b=a+1 print(b)")(a)

EDIT: fixed the last code snippet
 
Last edited:
Top