lua 子程序提高代码灵活性 写法

动态 未结 0 117
小小草
小小草 LV1 2023年9月23日 23:40 发表
以下是一些LUA子程序提高代码灵活性的写法: 1. 函数作为参数 ``` function sort(data, compare) table.sort(data, compare) end local data = {3, 1, 4, 2} sort(data, function(a, b) return a < b end) print(table.concat(data, ", ")) ``` 在上面的例子中,`sort`函数接受一个比较函数作为参数,以便根据不同的比较规则对数据进行排序。 2. 函数返回函数 ``` function factory(value) return function() return value end end local f1 = factory(10) local f2 = factory(20) print(f1()) -- 输出 10 print(f2()) -- 输出 20 ``` 在上面的例子中,`factory`函数返回一个新的函数,该函数执行某些操作并返回结果。在这种情况下,返回的函数只是返回传递给`factory`函数的值。 3. 闭包 ``` function counter() local count = 0 return function() count = count + 1 return count end end local c1 = counter() local c2 = counter() print(c1()) -- 输出 1 print(c1()) -- 输出 2 print(c2()) -- 输出 1 print(c1()) -- 输出 3 ``` 在上面的例子中,`counter`函数返回一个闭包,每次调用该闭包时都会增加计数器的值。 4. 递归 ``` function traverse(node, callback) if node == nil then return end callback(node) for _, child in ipairs(node.children) do traverse(child, callback) end end local tree = { children = { {value = 1}, {value = 2, children = { {value = 3}, {value = 4} }}, {value = 5} } } traverse(tree, function(node) print(node.value) end) ``` 在上面的例子中,`traverse`函数是一个递归函数
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复