lua 调用C/C++

/**
* Copyright (c) By zengqh.
*
* This program is just for fun or demo, in the hope that it  
* will be useful, you can redistribute it and/or modify freely.
*
* Time: 2012/06/26
* File: demo.cpp
* Blog: http://www.cnblogs.com/zengqh/
**/


#include <Windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <lua.hpp>


int hello1(lua_State* L)
{
    printf("hello1\n");

    return 0;
}

int hello2(lua_State* L)
{
    printf("hello2\n");

    return 0;
}

static const luaL_Reg functions[] =
{
    {"hello1", hello1},
    {"hello2", hello2}
};

int main()
{
    lua_State * L = lua_open();
    luaL_openlibs(L);

    /* love table */
    lua_newtable(L);
    lua_pushvalue(L, -1);
    lua_setglobal(L, "love");

    lua_newtable(L);

    luaL_register(L, 0, functions);

    lua_pushvalue(L, -1);

    lua_setfield(L, -3, "graphics");

    /* empty the stack */
    lua_pop(L, 2);

    if(luaL_loadfile(L, "test.lua") == 0)
    {
        lua_call(L, 0, 0);
    }    

    system("pause");
}

 

test.lua:

function print_hello1()
    love.graphics.hello1()
end

function print_hello2()
    love.graphics.hello2()
end

print_hello1()
print_hello2()  

 

output:

hello1
hello2

posted on 2012-06-26 22:11  zengqh  阅读(229)  评论(0编辑  收藏  举报