百度空间 | 百度首页 
 
查看文章
 
【转】c中读取Lua的全局变量数组
2009年09月21日 星期一 下午 06:40

原帖:http://blog.csdn.net/SpiriTRinG/archive/2009/03/14/3990733.aspx

配置实际上是非常简单的,添加好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)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu