c取Lua的全局变量数组

来源:互联网 发布:小啰啰崩没哏网络直播 编辑:程序博客网 时间:2024/06/07 07:22

配置实际上是非常简单的,添加好lib和头文件就ok了。

注意如果您是使用动态库,需要配置dll,最好的方式是把dll放在编译目录下,

这样发布您的程序就不会忘记这些杂七杂八的dll了。

 

Lua文件:luatext.lua

 

----------------------------------------------------------------------------------

gnum = 1


background = {r=1, g=2, b=3}

tab = {a=44 ,b=33 ,c=22,1, 2, 3, 4, 5, 6, 7, 8, 9, 0}

 

----------------------------------------------------------------------------------

 

c文件:lua.cpp

 

----------------------------------------------------------------------------------

 

#include <stdio.h>
#include <iostream>
#include <stdarg.h>

#pragma comment(lib,"lua51.lib")

extern "C" 
{
#include "lua.h"    
#include "lualib.h"    
#include "lauxlib.h"
}
using namespace std;

lua_State *L;

int getGlobal(lua_State *l,char * varname)
{
    static int count = 0;
    lua_getglobal(l, varname);
    return ++count;
}

float getGlobalNumber(lua_State *l ,char * varname)
{
    return (float)lua_tonumber    (l, getGlobal(l, varname));



float getField (const char *key) 
{
    float result = 0.0f;
    lua_pushstring(L, key);
    lua_gettable(L, -2);
    result = (float)lua_tonumber(L, -1);
    lua_pop(L, 1);
    return result;
}

float getNumber (const lua_Number num) 
{
    float result = 0.0f;
    lua_pushnumber(L, num);
    lua_gettable(L, -2);
    result = (float)lua_tonumber(L, -1);
    lua_pop(L, 1);
    return result;
}

int main (void) 
{
////////////////////////////////////////////////////////////////

    L = lua_open();
    luaL_openlibs (L);
    luaL_loadfile(L, "luatext.lua");
    lua_pcall(L, 0, 0, 0);
    
    lua_getglobal(L, "background");
    cout<<getField("r")<<endl;
    cout<<getField("g")<<endl;
    cout<<getField("b")<<endl;

    lua_getglobal(L, "tab");
    cout<<getField("a")<<endl;
    cout<<getField("b")<<endl;
    cout<<getField("c")<<endl;
    for(int i =1 ; i<=10 ; i++)
        cout<<getNumber(i)<<endl;


///////////////////////////////////////////////////////////////
    lua_close(L);
    getchar();
    return 0;
}

 

----------------------------------------------------------------------------------

0 0
原创粉丝点击