main.c
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static int l_split(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); //结果表
//依次处理每个分割符
while ((e = strchr(s, *sep)) != NULL)
{
lua_pushlstring(L, s, e - s); //压入子串
lua_rawseti(L, -2, i++); //向表中压入
s = e + 1; //跳过分隔符
}
//插入最后一个子串
lua_pushstring(L, s);
lua_rawseti(L, -2, i);
return 1; //将结果表返回
}
static luaL_Reg libs[] =
{
{"split", l_split},
{NULL, NULL}
};
__declspec(dllexport)//这个很重要,设置这个函数为外部链接 Linux不需要
int luaopen_mystring(lua_State* L) //函数名很重要这4个一定要这样,
{
luaL_newlib(L, libs);
return 1;
}
test_mystring.lua
local mystring = require("mystring")
local tb = mystring.split("http://www.runoob.com", ".") --执行后tb={"http://www", "runoob", "com"}
for i, v in ipairs(tb) do
print(i, v) --1是位置,v是值
end
运行结果:
D:\lua_test>lua test_mystring.lua
1 http://www
2 runoob
3 com
相关函数用法介绍:
C 库函数 char *strchr(const char *str, int c) 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。
举例:
#include <stdio.h>
#include <string.h>
int main()
{
const char str[] = "http://www.baidu.com";
const char ch = '.';
char *ret;
ret = strchr(str, ch);
printf("ret = %s\n", ret);
char *ret2 = strchr(ret+1, ch);
printf("ret2 = %s\n", ret2);
getchar();
return(0);
}
运行结果:
ret = .baidu.com
ret2 = .com
现在清楚这个函数的作用了。
lua_rawseti
原型: void lua_rawseti (lua_State *L, int index, int n);
描述: 为table中的key赋值. t[n] = v .其中t是index处的table , v为栈顶元素.
这个函数不会触发newindex元方法.
调用完成后弹出栈顶元素.