标签:os io ar cti sp on amp c new
1.C\C++程序中调用Lua函数
方法一:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lua.hpp"
const char* lua_function_code = "function dealStr(str) \
return string.gsub(str,\"World\",\"lua\") \
end";
void call_function(lua_State* L)
{
if (luaL_dostring(L,lua_function_code))
{
printf("Failed to run lua code.\n");
return;
}
char str[512] = "Hello World!";
lua_getglobal(L,"dealStr");
lua_pushlstring(L,str,512);
if(lua_pcall(L,1,1,0))
{
printf("error is %s.\n",lua_tostring(L,-1));
return;
}
if(!lua_isstring(L,-1))
{
printf("function ‘add‘ must return a string.\n");
return;
}
size_t len;
const char* ret = lua_tolstring(L,-1,&len);
lua_pop(L,-1); //弹出返回值。
printf("The result of call function is %s.\n",ret);
}
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
call_function(L);
lua_close(L);
system("pause");
return 0;
}
方法二:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "lua.hpp"
void call_function(lua_State* L)
{
luaL_dofile(L, "test.lua");
char str[512] = "Hello World!";
lua_getglobal(L,"dealStr");
lua_pushlstring(L,str,512);
if(lua_pcall(L,1,1,0))
{
printf("error is %s.\n",lua_tostring(L,-1));
return;
}
if(!lua_isstring(L,-1))
{
printf("function ‘add‘ must return a string.\n");
return;
}
size_t len;
const char* ret = lua_tolstring(L,-1,&len);
lua_pop(L,-1); //弹出返回值。
printf("The result of call function is %s.\n",ret);
}
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
call_function(L);
lua_close(L);
system("pause");
return 0;
}
test.lua
function dealStr(str)
return string.gsub(str,"World","lua")
end
标签:os io ar cti sp on amp c new
原文地址:http://www.cnblogs.com/elitiwin/p/3957860.html