Assigning function to Global Variable in Lua

Viewed 727

This is the sample test code.

s="\\command{sample execution}"
u=string.gsub(s,"\\(%b{})",print)

It works fine as print is global function. I defined function myprint as follows.

myprint = function(x,y)
  return print(x,y)
end

Now the command u=string.gsub(s,"\\(%b{})",myprint) does not work. This is because the myprint is not global variable as the print is. So basic question that I want to ask is "How to assign function to global variable in Lua?"

1 Answers

You just need to write:

global_function_1 = function (arg)
    -- body
end

or use the syntactic sugar alternative:

function global_function_2 (arg)
    -- body
end

Make sure that the part in which you do that doesn't have a local variable with selected name. For instance none of the following functions are global:

local bar
local function foo (arg)
    local zee
    function arg () end
    zee = function () end
    function bar () end
end

Please note that I have totally ignored assigning to table members and ignored existence of _G and _ENV, and let's leave it this way.

I think that it is worth mentioning that the string.gsub (or really any function call) doesn't care whenever the function (or any argument) is local or whatever:

local str = "abc"
local function fn (x) print(x) end
string.gsub(str, "%a", fn)

outputs:

a
b
c
Related