lua语言三则特性

pack和unpack

对于一个函数, 要将其入参转换为一个表, 则pack函数合适。

对于一个表要将其转换为 一个函数的入参, 则 lua原生提供的 unpack函数可以实现。

do

arrayData = {"a", "b", "c", "d", "e"};

function pack(...)

  return {...};

end

print( pack("aa", "bb")[2] );

--print((returnMoreValues()));

--print(arrayData); -- print the address of the arrayData

--print(unpack(arrayData)); -- print all the elements of the arrayData

print(unpack(arrayData, 2)); --the second param is the index of the arrayData

end

 

 

>lua -e "io.stdout:setvbuf 'no'" "luatest.lua" 

b c d e

>Exit code: 0

>lua -e "io.stdout:setvbuf 'no'" "luatest.lua" 

aa

b c d e

>Exit code: 0

>lua -e "io.stdout:setvbuf 'no'" "luatest.lua" 

bb

b c d e

>Exit code: 0

lua脚本函数也可以序列化

函数序列化, 可以实现函数的跨进程功能。 如果此函数是动态的产生的, 并且需要跨进程访问。

http://www.cnblogs.com/luweimy/p/4104642.html

序列化加密
string.dump(loadstring(ret))

这就是加密的代码,因为string.dump参数必须是function, 所以使用loadstring将字符串加载成chunk,然后在由string.dump导成字节码
其实就是使用了string.dump函数,它可以把function导成二进制字节码,使用它处理一下就可以把明文字符串转成字节码了

local function ser(var, enc)

assert(type(var)=="table")

-- 标记所有出现的table, 并记录其key, 用于处理循环引用

local mark = {}

-- 用于记录循环引用的赋值语句

local assign = {}

-- 序列化表, ret字符串必须与后面的loca ret=%s中的ret相同,因为这个ret可能也会组织到结果字符串中。

local ret = table_ser(var, "ret", mark, assign)

local ret = string.format("local ret=%s %s return ret", ret, table.concat(assign, ";"))

return (enc==nil or enc==true) and string.dump(loadstring(ret)) or ret

end

https://github.com/Luweimy/luaser/blob/master/luaser.lua

luaL_register 接口 可以多次调用 给指定的模块 添加新接口

http://www.lua.org/manual/5.1/manual.html#lua_register

void luaL_register (lua_State *L,
                    const char *libname,
                    const luaL_Reg *l);

Opens a library.

When called with libname equal to NULL, it simply registers all functions in the list l (see luaL_Reg) into the table on the top of the stack.

When called with a non-null libname, luaL_register creates a new table t, sets it as the value of the global variable libname, sets it as the value of package.loaded[libname], and registers on it all functions in the list l. If there is a table in package.loaded[libname] or in variable libname, reuses this table instead of creating a new one.

In any case the function leaves the table on the top of the stack.

If there is a table in package.loaded[libname] or in variable libname, reuses this table instead of creating a new one.

原文地址:https://www.cnblogs.com/lightsong/p/5628660.html