码迷,mamicode.com
首页 > 编程语言 > 详细

c++调用lua的基本操作

时间:2016-03-03 22:58:51      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:

目标: 用c++读取下面lua文件的变量,表,调用函数:

由于还有些表要我配,今天任务延期,没完成,明日再更新

name = "织法"
age = 25
color = {r=1.0,g=0.2,b=0.5,a=1.0}
arr = {1,2,3,4,5}
function Add(a,b)
    return a+b
end
function Squar(num)
    return num * num
end
function Dist2D(pointA,pointB)
    local xdst = pointA.x - pointB.x
    local ydst = pointA.y - pointB.y
    return math.sqrt(Squar(xdst) + Squar(ydst))
end
print("hello lua")

c++ luabase.h

#pragma once
#include<string>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
#include "lua.hpp"

extern lua_State *L;

struct luaColor
{
    double r, g, b, a;
    void output();
};

bool lua_checkf(int err);
#define LUA_CHECK(f) do{if(!lua_checkf(f))        return false;}while(0)
void loadLua();
void cloaseLua();
int loadInteger(const char* v_key);
const char* loadString(const char* v_key);
int lua_add(int a, int b);
bool loadColor(luaColor *v_color);

c++ luabase.cpp

#include"luabase.h"

lua_State *L;

bool lua_checkf(int err)
{
    if (!err)
    {
        printf("报错啦,错误信息是%s\n", lua_tostring(L, -1));
        return false;
    }
    return true;
}

#define LUA_CHECK(f) do{if(!lua_checkf(f))        return false;}while(0)


void loadLua()
{
    const string filename = "lua/test.lua";
    L = luaL_newstate();
    luaopen_base(L);
    luaL_openlibs(L);
    luaL_dofile(L, filename.data());
}

void cloaseLua()
{
    lua_close(L);
}

int loadInteger(const char* v_key)
{
    LUA_CHECK(lua_getglobal(L, v_key));
    int rst = lua_tointeger(L, -1);
    lua_pop(L, 1);
    return rst;
}

const char* loadString(const char* v_key)
{
    LUA_CHECK(lua_getglobal(L, v_key));
    lua_pop(L, 1);
    return lua_tostring(L, -1);
}

int lua_add(int a,int b)
{
    lua_getglobal(L, "Add");
    lua_pushinteger(L, a);
    lua_pushinteger(L, b);
    if (lua_pcall(L, 2, 1, 0) != LUA_OK)
    {
        printf("报错啦,错误信息是%s\n",lua_tostring(L, -1));
    }
    int rst = lua_tointeger(L, -1);
    lua_pop(L, 3);
    return rst;
}

static double getDoubleField()
{

}

bool loadColor(luaColor *v_color)
{
    LUA_CHECK(lua_getglobal(L, "color"));
    LUA_CHECK(lua_getfield(L, -1, "r"));
    v_color->r = lua_tonumber(L, -1);
    lua_pop(L, 1);
    LUA_CHECK(lua_getfield(L, -1, "g"));
    v_color->g = lua_tonumber(L, -1);
    lua_pop(L, 1);
    LUA_CHECK(lua_getfield(L, -1, "b"));
    v_color->b = lua_tonumber(L, -1);
    lua_pop(L, 1);
    LUA_CHECK(lua_getfield(L, -1, "a"));
    v_color->a = lua_tonumber(L, -1);
    lua_pop(L, 1);
    lua_pop(L, 1);
    return true;
}

void luaColor::output()
{
    printf("color:{%d,%d,%d,%d}", (int)(r*255), (int)(g*255), (int)(b*255), (int)(a*255));
}

 

c++调用lua的基本操作

标签:

原文地址:http://www.cnblogs.com/mizime/p/5240187.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!