---
title: "lua函数"
author: "catdoc"
date: "2014-08-30T00:14:33Z"
tags: []
categories: ["移动开发"]
slug: "lua"
draft: false
lastmod: "2014-08-30T00:14:33Z"
id: 2110963
url: "https://catdoc.iteye.com/blog/2110963"
---

第一类值：函数可以存储到变量中，可作为实参传递，还可以作为函数返回值。
词法域：  函数可以嵌套，内部的函数可以访问外部函数中的变量。

高阶函数 ： table.sort( t, function(a, b) return (a.name > b.name) end)

closure闭合函数：
 
function sortbygrade ( names, grades)
   table.sort ( names, function ( n1, n2) return grades > grades end )
end 

grades 既不是全局变量也不是局部变量，--> 非局部的变量, 也称为 upvalue. 
一个closure就是一个函数加上该函数所需访问的所有 非局部的变量. 

Technically speaking, what is a value in Lua is the closure, not the function.
The function itself is just a prototype for closures.

将函数存储在普通变量中，重新定义某些函数，利用该技术创建一个安全的沙盒(sandbox).

do 
    local oldOpen = io.open
    local access_OK = function ( filename, mode)
        // do something
    end
    io.open = function ( filename, mode)
                           if access_OK(filename, mode) then
                                   return oldOpen( filename, mode)
                           else
                                   return nil, "access, denied"
                           end
                      end
end 

大部分lua库采用的机制：将函数存储在table字段中
Lib = {}
Lib.foo = function (x, y) return x + y end
Lib.goo = function (x, y) return x * y end
或另一种语法:
Lib = {}
function Lib.foo( x, y) return x + y end
function Lib.goo( x, y) return x * y end

局部函数定义： local function foo () <函数体> end 

间接递归和前向声明：
local f, g
function g()
    f()
end
function f()
    g()
end