louis058
louis058

Reputation: 67

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.

Upvotes: 0

Views: 1410

Answers (2)

lhf
lhf

Reputation: 72312

The same thing can be accomplished with

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

Upvotes: 1

Nathan Wiebe
Nathan Wiebe

Reputation: 802

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.

Upvotes: 2

Related Questions