Walkerbo
Walkerbo

Reputation: 653

Lua - Basic Table of Functions

I am trying to understand how a Lua table of functions correctly work.

I want to be able to define functions and then list those functions in a table so when I iterate through the table I can run each function.

This is my code:

function qwe()
   print ("qwe fired")
end

function asd() 
   print ("asd fired")
end

local tab = {
   qwe(),
   asd(),
}

function zxc()
   print ("zxc start")    
   for k,v in pairs (tab) do
      return v
   end
   print ("zxc end")
end

I know that this is more than likely very basic sort of thing but I have no real programming background,(I am trying to self learn Lua),and most of the references and examples seem to rely on a basic understanding that I am lacking.

Upvotes: 2

Views: 3721

Answers (2)

Walkerbo
Walkerbo

Reputation: 653

Here are my 2 solutions based on Paul's answer.

-- load functions directly

function foo()
    print("foo fired")
end

function goo()
    print("goo fired")
end

function poo()
    print("poo fired")
end

local roo = {
    "foo()",
    "goo()",
    "poo()",
}

function zoo ()
    print("\n ***** load function directly *****")
    for k,v in pairs (roo) do
        print(k,v)
        load(v)()
    end
print(" *** end ***\n\n")
end

-- load concatenated string

function foo()
    print("foo fired")
end

function goo()
    print("goo fired")
end

function poo()
    print("poo fired")
end

local roo = {
    "foo",
    "goo",
    "poo",
}

function zoo ()
    print("\n ***** load concatenated string *****")
    for k,v in pairs (roo) do
        print(k,v)
        load(v.."()")()
    end
    print(" *** end ***\n\n")
end

Upvotes: 0

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

local tab = {
   qwe(),
   asd(),
}

You are assigning the results of functions to the table instead of the function references. You should be doing:

local tab = {
   qwe,
   asd,
}

If you then need to call these values, you just use them as a function:

tab[1]() -- call `qwe` and discard results
-- or
tab[2]() -- call `asd` and discard results
-- or
for k,v in pairs (tab) do
  return v() -- call first function and return its result(s)
end

Upvotes: 4

Related Questions