简体   繁体   中英

Defining a function within a loop using loadstring with Lua 5.1

I'm currently trying to define a function using a combination of concatenation, loadstring, and a for loop.

This is the kind of thing I have currently:

> for f=1,8 do
loadstring("function f" .. f .. " () print('" .. f .. "') end")
end
> f1()
stdin:1: attempt to call global 'f1' (a nil value)
stack traceback:
    stdin:1: in main chunk
    [C]: ?

The function evaluates a set of chunks in the form of: 'function f () print() end'. However, as you can see, it doesn't seem to save the function into the variables f1-f8 correctly.

The loadstring() function returns a function that, when called, executes the code given as an argument. It doesn't actually call the function or run the code. Try the following:

for f=1,8 do
loadstring("function f" .. f .. " () print('" .. f .. "') end")()
end

The added parenthesis calls the function that has just been created by loadstring(), creating your numbered functions.

The same thing can be accomplished with

for f=1,8 do
   _G["f"..f]=function () print(f) end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM