一. lua调用C++
在lua中是以函数指针的形式调用函数, 并且所有的函数指针都必须满足如下此种类型:
typedef int (*lua_CFunction) (lua_State *L);
也就是说, 偶们在C++中定义函数时必须以lua_State为参数, 以int为返回值才能被Lua所调用. 但是不要忘记了, 偶们的lua_State是支持栈的, 所以通过栈可以传递无穷个参数, 大小只受内存大小限制. 而返回的int值也只是指返回值的个数真正的返回值都存储在lua_State的栈中. 偶们通常的做法是做一个wrapper, 把所有需要调用的函数都wrap一下, 这样就可以调用任意的函数了.
- #include<iostream>
- using namespace std;
- #include<stdio.h>
- extern "C" {
- #include <lua.h>
- #include <lualib.h>
- #include <lauxlib.h>
- }
-
- lua_State* L;
- static int average(lua_State *L)
- {
-
- int n = lua_gettop(L);
- double sum = 0;
- int i;
- for (i = 1; i <= n; i++)
- {
- if (!lua_isnumber(L, i))
- {
- lua_pushstring(L, "Incorrect argument to 'average'");
- lua_error(L);
- }
- sum += lua_tonumber(L, i);
- }
-
- lua_pushnumber(L, sum / n);
-
- lua_pushnumber(L, sum);
-
-
- return 2;
- }
- int main (int argc,char*argv[])
- {
-
- L = lua_open();
-
- luaL_openlibs(L);
-
- lua_register(L, "average", average);
-
- luaL_dofile(L, "e15.lua");
-
- lua_getglobal(L,"avg");
- cout<<"avg is:"<<lua_tointeger(L,-1)<<endl;
- lua_pop(L,1);
- lua_getglobal(L,"sum");
- cout<<"sum is:"<<lua_tointeger(L,-1)<<endl;
-
- lua_close(L);
-
- return 0;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
脚本为
avg, sum = average(10, 20, 30, 40, 50)
print("The average is ", avg)
print("The sum is ", sum)
二. C++调用lua
- #include "stdafx.h"
- #include <stdio.h>
- extern "C" {
- #include "lua.h"
- #include "lualib.h"
- #include "lauxlib.h"
- }
-
- lua_State* L;
- int main ( int argc, char *argv[] )
- {
-
- L = lua_open();
-
- luaL_openlibs(L);
-
- luaL_dofile(L, "Lua1.lua");
-
- lua_close(L);
-
- printf( "Press enter to exit…" );
- getchar();
- return 0;
- }
-
- #include <stdio.h>
- extern "C" {
- #include <lua.h>
- #include <lualib.h>
- #include <lauxlib.h>
- }
- #include <stdio.h>
- extern "C" {
-
- #include "lua.h"
- #include "lualib.h"
- #include "lauxlib.h"
- }
- #pragma comment(lib, "lua5.1.lib")
-
- lua_State* L;
- int luaadd ( int x, int y )
- {
- int sum;
-
- lua_getglobal(L, "add"); int nTop = lua_gettop(L);
-
- lua_pushnumber(L, x); nTop = lua_gettop(L);
-
- lua_pushnumber(L, y); nTop = lua_gettop(L);
-
-
- lua_call(L, 2, 1); nTop = lua_gettop(L);
-
- sum = (int)lua_tonumber(L, -1); nTop = lua_gettop(L);
-
- lua_pop(L, 1); nTop = lua_gettop(L);
-
- lua_getglobal(L, "z"); nTop = lua_gettop(L);
- int z = (int)lua_tonumber(L, 1);nTop = lua_gettop(L);
- lua_pop(L, 1); nTop = lua_gettop(L);
-
-
-
-
-
- return sum;
- }
- int main ( int argc, char *argv[] )
- {
- int sum;
-
- L = lua_open();
-
-
-
- luaL_dofile(L, "e12.lua");
-
- sum = luaadd( 10, 15 );
-
- printf( "The sum is %d", sum );
-
- lua_close(L);
- return 0;
- }
-
-
-
-
-
-
-
-
脚本为:
-- add two numbers
function add ( x, y )
return x + y + 2
end
z = 6