标签 lua 下的文章

Lua有两种执行系统命令的方法:os.execute, io.popen

os.execute 返回的是命令执行的状态,一共返回3个值。
第一个值是truenil, true表示命令成功执行完,否则返回nil
第二个值是exit时,表示正常终止,第三个值表示退出的状态码。
第二个值是signal时,表示信号终止,第三个值表示终止的信号。

例如

> os.execute("pwd")
true exit 0
> os.execute("pwdx")
nil exit 127

io.popen 启动一个新进程执行命令,并返回一个文件句柄,可以使用该文件句柄读取返回的数据。
例如,或通过这个方法获得文件列表

local f = io.popen("ls")
print(f:read("*a")

使用table.sort时,碰到一个错误:invalid order function for sorting
原因是table.sort的比较函数返回的类型不是boolean

正确使用table.sort的方法:

-- 按数字大小降序排序
local t = { 1, 10, 8, 7}
table.sort(t, function (a, b)
    return a - b > 0
end)

-- 按数字大小升序排序
table.sort(t, function (a, b)
    return a - b < 0
end)

select(index, ...)

如果index是正数,那么返回从左边第index个到最右边的参数;
如果index是负数,那么返回从右边第index个到最左边的参数;
如果index是字符串"#", 那么返回可变参数...的参数个数
例如:

function test(...)
    print(select("#", ...))
    -- 输出为:
    -- 4

    for i=1, select("#", ...) do
        print(select(i, ...))
    end
    -- 输出为:
    -- 1    2    3    4
    -- 2    3    4
    -- 3    4
    -- 4

    for i=1, select("#", ...) do
        print(select(-i, ...))
    end
    -- 输出为:
    -- 4
    -- 3    4
    -- 2    3    4
    -- 1    2    3    4
end

test(1, 2, 3, 4)

Luajit 是针对Lua开发的一款即时编译器, 提供了FFI库, 可以方便使用C接口的动态库.

先准备一个C语言的库
mytest.c

int add(int x, int y)
{
    return x + y;
}

编译动态库文件libmytest.so

g++ mylib.c --shared -o libmytest.so

Lua文件test.lua

local ffi = require("ffi")
local mytest = ffi.load('mytest')

ffi.cdef[[
int add(int x, int y);
]]

local result = mytest.add(1, 2)

print(result)

执行test.lua

luajit test.lua

如果出现动态库找不到的情况下,可以执行下面的命令:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<动态库所有目录>