function fnex2(str_a, num_b, num_c)
print(str_a);
return num_b*100 + num_c*10, "Thank you";
end;
print (">>> LUA程序开始运行了 ");
function fnex3(num_a, num_b)
local c = rmath(num_a, num_b);
print("LUA PRINTTING:", c);
return c;
end;
//LUA脚本调用C函数
int call_c_function(void)
{
int iArg1 = 3, iArg2 = 10, iError;
cout << "=================================" << endl
<< "下面的程序演示从LUA脚本中调用C函数" << endl
<< "Argument 1:" << iArg1 << endl
<< "Argument 2:" << iArg2 << endl
<< "---------------------------------" << endl
<< "#OUTPUTS#" << endl;
lua_State* L = lua_open();
InitLuaState(L);
iError = luaL_loadfile(L, "../test03.lua");
if (iError) cout << "载入脚本失败" << endl;
iError = lua_pcall(L, 0, 0, 0);
if (iError) cout << "执行LUA脚本失败" << endl;
/* 将C函数(指针)压栈 */
lua_pushstring(L, "rmath");
lua_pushcfunction(L, RMath_LUA);
lua_settable(L, LUA_GLOBALSINDEX);
/* LUA函数也是变量(指针),可以压入栈 */
lua_getglobal(L, "fnex3");
/* 将提供给LUA函数的参数入栈 */
lua_pushnumber(L, iArg1);
lua_pushnumber(L, iArg2);
/* 调用LUA函数(pcall函数会自动清除入栈的变量) */
int Error = lua_pcall( L, //虚拟机指针
2, //2个参数
1, //1个返回值
0 );
if (Error) cout << "pcall调用fnex3函数失败" << endl;
/* 检验返回值类型 */
if (lua_isnumber(L, -1))
{
cout << "有1个(double)返回值 = "
<< lua_tonumber(L, -1)
<< endl;
}
/* 将LUA函数返回值出栈 */
lua_pop(L, 1);
lua_close(L);
return 0;
}
//可供LUA调用的C函数原型
int RMath_LUA(lua_State* L)
{
if (!lua_isnumber(L, 1))
{
lua_pushstring(L, "Arg_1不是数字");
lua_error(L);
}
if (!lua_isnumber(L, 2))
{
lua_pushstring(L, "Arg_2不是数字");
lua_error(L);
}
/* GET ARGUMENT FROM STACK */
double a = lua_tonumber(L, 1);
double b = lua_tonumber(L, 2);
/* PUSH RESULT TO STACK */
lua_pushnumber(L, a * b);
/* COUNT OF RETURN VARS*/
return 1;
}
/* Push a FUNCTION_VAR to STACK */
lua_getglobal(L, "fnex2");
/* Push PARAMETERS to STACK */
lua_pushstring(L, szInParam);
lua_pushnumber(L, iParam1);
lua_pushnumber(L, iParam2);
/* Call FUNCTION in LUA */
iError = lua_pcall( L,3,2,0);