1. 程式人生 > >lua 與 c/c++ 互動(6) lua呼叫C++(使用陣列 和字串函式)

lua 與 c/c++ 互動(6) lua呼叫C++(使用陣列 和字串函式)

lua呼叫 c++ 的 兩個函式: 一個是 對lua 陣列 呼叫函式替換 陣列元素,一個 分割字串

test.lua

--陣列操作
a = {1,2,3,4,5,6}
swapArray(a,function(t)
	return t + 1
  end)

local function printArray(array)
	for k,v in ipairs(array) do
		print(k,"\t",v,"\n")
	end
end

printArray(a)

--分割字串
a = split("a,b,c,d,e,fgh,ijk",",")
printArray(a)
	

cpp

// LuaCApi.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <string>
using namespace std;
extern "C"{
	#include "lua\lua.h"
	#include "lua\lauxlib.h"
	#include "lua\lualib.h"
}

void error(lua_State * l,const char * fmt,...){
	va_list va;
	va_start(va,fmt);
	vfprintf(stderr,fmt,va);
	va_end(va);
	lua_close(l);
	exit(EXIT_FAILURE);
}


int swapArray(lua_State *l){
	luaL_checktype(l,1,LUA_TTABLE);
	luaL_checktype(l,2,LUA_TFUNCTION);
	int len = lua_objlen(l,1);
	for (int i = 1; i <= len; i++)
	{
		lua_pushvalue(l,2);
		lua_rawgeti(l,1,i);
		if (lua_pcall(l,1,1,0))
		{
			printf("error :%s",lua_tostring(l,-1));
		}
		lua_rawseti(l,1,i);
	}
	return 0;
}

int split(lua_State *l){
	const char * s = luaL_checkstring(l,1);
	const char * sep = luaL_checkstring(l,2);
	const char * index = NULL;
	int count = 1;
	lua_newtable(l);
	while ((index = strchr(s,*sep)) != NULL)
	{
		lua_pushlstring(l,s,index-s);
		lua_rawseti(l,-2,count++);
		s = index + 1;
	}
	lua_pushstring(l,s);
	lua_rawseti(l,-2,count);
	return 1;

}

int _tmain(int argc, _TCHAR* argv[])
{
	lua_State * l  = luaL_newstate();
	luaL_openlibs(l);
	lua_register(l,"swapArray",swapArray);
	lua_register(l,"split",split);
	if (luaL_loadfile(l,"test.lua") || lua_pcall(l,0,0,0))
	{
		error(l,"error : %s",lua_tostring(l,-1));
	}
	
	return 0;
}