您的位置:首页 > 编程语言 > Lua

lua学习笔记1

2014-11-04 21:27 363 查看
lua中调用c的函数

#include <stdio.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
}
#else
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#endif
static int l_testluaCFun(lua_State *L)
{
double d = lua_tonumber(L, 1);
lua_pushnumber(L, d);
return 1;
}
static int add2(lua_State* L)
{
//检查栈中的参数是否合法,1表示Lua调用时的第一个参数(从左到右),依此类推。
//如果Lua代码在调用时传递的参数不为number,该函数将报错并终止程序的执行。
double op1 = luaL_checknumber(L, 1);
double op2 = luaL_checknumber(L, 2);
//将函数的结果压入栈中。如果有多个返回值,可以在这里多次压入栈中。
lua_pushnumber(L, op1 + op2);
//返回值用于提示该C函数的返回值数量,即压入栈中的返回值数量。
return 1;
}
const char* testfunc = "print(add2(1.0,2.0))";
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, l_testluaCFun);
lua_setglobal(L, "testluaCFun");
lua_register(L, "add2", add2);
luaL_dofile(L, "E:\\Sublime_lua\\1.lua");
if (luaL_dostring(L, testfunc))
printf("Failed to invoke.\n");
system("pause");
lua_close(L);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: