1. 数组操作:
在Lua中,“数组”只是table的一个别名,是指以一种特殊的方法来使用table。出于性能原因,Lua的C API为数组操作提供了专门的函数,如:
void lua_rawgeti(lua_State* L, int index, int key);
void lua_rawseti(lua_State* L, int index, int key);
以上两个函数分别用于读取和设置数组中的元素值。其中index参数表示待操作的table在栈中的位置,key表示元素在table中的索引值。由于这两个函数均为原始操作,比涉及元表的table访问更快。通常而言,作为数组使用的table很少会用到元表。
见如下代码示例和关键性注释:
#include <stdio.h>
#include <string.h>
#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>
extern "C" int mapFunc(lua_State* L)
{
//检查Lua调用代码中传递的第一个参数必须是table。否则将引发错误。
luaL_checktype(L,1,LUA_TTABLE);
luaL_checktype(L,2,LUA_TFUNCTION);
//获取table中的字段数量,即数组的元素数量。
int n = lua_objlen(L,1);
//Lua中的数组起始索引习惯为1,而不是C中的0。
for (int i = 1; i <= n; ++i) {
lua_pushvalue(L,2); //将Lua参数中的function(第二个参数)的副本压入栈中。
lua_rawgeti(L,1,i); //压入table[i]
lua_call(L,1,1); //调用function(table[i]),并将函数结果压入栈中。
lua_rawseti(L,1,i); //table[i] = 函数返回值,同时将返回值弹出栈。
}
//无结果返回给Lua代码。
return 0;
}
2. 字符串操作:
当一个C函数从Lua收到一个字符串参数时,必须遵守两条规则:不要在访问字符串时从栈中将其弹出,不要修改字符串。在Lua的C API中主要提供了两个操作Lua字符串的函数,即:
void lua_pushlstring(lua_State *L, const char *s, size_t l);
const char* lua_pushfstring(lua_State* L, const char* fmt, ...);
第一个API用于截取指定长度的子字符串,同时将其压入栈中。而第二个API则类似于C库中的sprintf函数,并将格式化后的字符串压入栈中。和sprintf的格式说明符不同的是,该函数只支持%%(表示字符%)、%s(表示字符串)、%d(表示整数)、%f(表示Lua中的number)及%c(表示字符)。除此之外,不支持任何例如宽度和精度的选项。
#include <stdio.h>
#include <string.h>
#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>
extern "C" int splitFunc(lua_State* L)
{
const char* s = luaL_checkstring(L,1);
const char* sep = luaL_checkstring(L,2); //分隔符
const char* e;
int i = 1;
lua_newtable(L); //结果table
while ((e = strchr(s,*sep)) != NULL) {
lua_pushlstring(L,s,e - s); //压入子字符串。
//将刚刚压入的子字符串设置给table,同时赋值指定的索引值。
lua_rawseti(L,-2,i++);
s = e + 1;
}
//压入最后一个子串
lua_pushstring(L,s);
lua_rawseti(L,-2,i);
return 1; //返回table。
}
Lua API中提供了lua_concat函数,其功能类似于Lua中的".."操作符,用于连接(并弹出)栈顶的n个值,然后压入连接后的结果。其原型为:
void lua_concat(lua_State *L, int n);
参数n表示栈中待连接的字符串数量。该函数会调用元方法。然而需要说明的是,如 |