Lua: function as argument of function

Viewed 62

Is it possible write a function as a function argument? Let me explain: this is my code

table = {
    yellow = {
        "banana",
        "lemon"
    },
    red = {
        "apple"
        },
    green = {
        "watermelon"
        }
}

function fruit(arg1) print(arg1) end

function scope(tbl, func)
  for k, v in pairs(tbl) do
    
    if (type(v) ~= "table") then
      func(v)
    else
      scope(v)
    end
    
  end
end

scope(table,fruit)

My output should be

  • banana
  • lemon
  • apple
  • watermelon

This is the error message

local 'func' is not callable (a nil value)

1 Answers

When scope calls scope you forgot to pass the argument func so it is nil.

scope(v)

is the same as

scope(v, nil)

while you probably meant

scope(v, func)
Related