14

编程小知识之 Lua 函数定义

 3 years ago
source link: https://blog.csdn.net/tkokof1/article/details/103170867
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

编程小知识之 Lua 函数定义

本文简单介绍了 Lua 函数定义的一点知识

在 Lua 中,我们定义函数的方式和在 C 语言中定义函数的方式很像:

local function func_name(func_param)
    -- func_body
end 

但实际上,这种定义方式仅是 Lua 提供的语法糖,实际执行时, Lua 会将上面的函数定义转换为匿名函数的形式:

-- define func_name
local func_name 
-- set func_name
func_name = function(func_param)
    -- func_body
end 

有时候我们也会手动定义匿名函数,但写法上往往会比上面的方式更简洁一些:

local func_name = function(func_param)
    -- func_body
end 

这里要注意的是,上面的这种函数定义方式和之前的两种函数定义并不等价,差别在于 func_name 对于函数体的可见性上(在上面的这种函数定义方式中, func_name 对于函数体并不可见)

一般情况下,这种差异并不会造成很大的问题,但是涉及定义递归函数时就要多加注意了.

下面是用递归实现的累计求和函数,有兴趣的朋友可以注意一下三种函数定义方式的表现差异:

-- method 1
local function sum(val)
    if val <= 1 then
        return val
    else
        return val + sum(val - 1)
    end
end 
-- method 2, same as method 1
local sum 
sum = function(val)
    if val <= 1 then
        return val
    else
        return val + sum(val - 1)
    end
end
-- method 3, will cause global "sum" access problem
local sum = function(val)
    if val <= 1 then
        return val
    else
        return val + sum(val - 1)
    end
end

在 Lua 中, 谨慎定义递归匿名函数


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK