lua调用C库之——字符串切割存到table中

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元方法.
调用完成后弹出栈顶元素.

参考:
lua 和 C 语言进行交互 —— 如何传递table

C 库函数 - strchr()

Lua笔记-关于lua table的C API

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值