天天看點

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

繼續閱讀