Class for lua to operate C ++; manipulate c ++ class with lua

Source: Internet
Author: User

Prepare cocos2dx lua, and compress lua for reference. (I am also a little confused. If you find anything inappropriate, please try your best. I accept all)


1. Version: This is a pitfall.

First of all, pil (programming in lua) Chinese (it seems to be a great success) translation version is 5.0 a little low.

Cocos2dx 2.15 uses lua 5.1,

The latest lua is 5.2,

The latest pil 3rd is also 5.2;

5.0; 5.1; 5.2 functions have changed a lot. when you first get started, you may encounter errors even when the copy code is run correctly. Check whether your code is consistent with the lua environment. Most of the code examples on the Internet are 5.0, which requires slight modification.


2. reading a book. lua is not big and complex. If you are not studying the implementation of lua code, you can get started quickly.

First, repeat the pil several times to get the correct syntax, and then look at the part bound to C. This section focuses on several concepts of resumable _ index _ newindex. You can.


3. c, c ++

This is actually the technique mentioned above (2). In essence, lua indirectly operates C ++ class through glue code.


Don't talk nonsense, just go to bed .... It is hard to tell. Check the code. Added detailed annotations.

Makefile

all:g++ -g3 -o cheneeout chenee.cpp  -lluaclean:rm -R *dSYM *out


Chenee. lua
print "test lua access C++ Class"local a = Animal("dog")--local a = Animal.creat("dog")a:setAge(100)a:sound()print ("age is :" .. a:getAge())



Chenee. cpp

////@chenee:this Demo showing how to manipulate the C++ class with LUA// LUA = the moon//#include <stdio.h>#include <string>#include <iostream>extern "C"{#include "lua.h"#include "lauxlib.h"#include "lualib.h"}//@chenee: to dump the lua stackstatic void stackDump(lua_State * L){inti;inttop = lua_gettop(L);/* depth of the stack */for (i = 1; i <= top; i++) {/* repeatforeachlevel */intt = lua_type(L, i);switch (t) {case LUA_TSTRING:{ /* strings */printf("'%s'", lua_tostring(L, i));break;}case LUA_TBOOLEAN:{ /* booleans */printf(lua_toboolean(L, i) ? "true" : "false");break;}case LUA_TNUMBER:{ /* numbers */printf("%g", lua_tonumber(L, i));break;}default:{/* other values */printf("%s", lua_typename(L, t));break;}}printf("  ");/* put a separator */}printf("\n");/* end the listing */}using namespace std;////@chenee: the class to be deal with;//class Animal{public:    Animal(std::string name):age(0){ this->name = name;};    void setAge(int age) { this->age = age;};    int getAge(){ return this->age;};    void sound(){ cout << " -- Animal name:   " << this->name << "  and it's Age:"<< this->age << endl;};private:    string name;    int age;};////@chenee: this class used as a tool to expose interfaces to lua//class LuaAnimal{    static const string className;    static const luaL_reg methods[];    static const luaL_reg methods_f[];    static int creat(lua_State *L){        string name (lua_tostring(L,1));        Animal *a = new Animal(name);        void **p = (void**)lua_newuserdata(L,sizeof(void*));        *p = a;      luaL_getmetatable(L, className.c_str());      lua_setmetatable(L, -2);      return 1;    }    static int gc_animal(lua_State *L) {        Animal *a = (Animal*)(*(void**)lua_touserdata(L,1));        delete a;//        cout << "Gc ....." << endl;        return 0;    }    static Animal* getAnimal(lua_State *L){        luaL_checktype(L,1,LUA_TUSERDATA);        void *ud = luaL_checkudata(L,1,className.c_str());        if(!ud){            luaL_typerror(L,1,className.c_str());        }        return *(Animal**)ud;    }    static int sound(lua_State *L){        Animal *a = getAnimal(L);        a->sound();        return 1;    }    static int setAge(lua_State *L){        Animal *a = getAnimal(L);        double age = luaL_checknumber(L, 2);        a->setAge(int(age));        return 0;    }    static int getAge(lua_State *L){        Animal *a = getAnimal(L);        int age = a->getAge();       lua_pushinteger(L, age);        return 1;    }public:    static void Register(lua_State* L) {        //1: new methods talbe for L to save functions        lua_newtable(L);        int methodtable = lua_gettop(L);        //2: new metatable for L to save "__index" "__newindex" "__gc" "__metatable" ...        luaL_newmetatable(L, className.c_str());        int metatable   = lua_gettop(L);        //3: metatable["__metatable"] = methodtable        lua_pushliteral(L, "__metatable");        lua_pushvalue(L, methodtable);        lua_settable(L, metatable);  // hide metatable from Lua getmetatable()        //4: metatable["__index"] = methodtable        lua_pushliteral(L, "__index");        lua_pushvalue(L, methodtable);        lua_settable(L, metatable);        //5: metatable["__gc"] = gc_animal         lua_pushliteral(L, "__gc");        lua_pushcfunction(L, gc_animal);        lua_settable(L, metatable);        lua_pop(L, 1);  // drop metatable        //6: for objct:        // name == 0 set object function to "methods"        //eg:Animal a = Animal("xx");        //a:func() in this "methods" table;        luaL_openlib(L, 0, methods, 0);  // fill methodtable        lua_pop(L, 1);  // drop methodtable        //7.1: for Class:        //name = "classname" , so this set Class function to "methods_f"        //eg:Animal a = Animal:creat("xx");        //Animal:creat() in this "methods_f" tables;//        luaL_openlib(L, className.c_str(), methods_f, 0);        //7.2: for Class:        //add global function "Classname", so we Animal() is a global function now        //Animal a = Animal("xx");        //function Animal()in lua will call "creat" in C++        lua_register(L, className.c_str(), creat);    }};const string LuaAnimal::className = "Animal";const luaL_reg LuaAnimal::methods[] = {    {"sound", LuaAnimal::sound},    {"setAge", LuaAnimal::setAge},    {"getAge", LuaAnimal::getAge},    {"__gc", LuaAnimal::gc_animal},    {NULL, NULL}};const luaL_reg LuaAnimal::methods_f[] = {    {"creat", LuaAnimal::creat},    {NULL, NULL}};int main(){lua_State      *L = luaL_newstate();    luaL_openlibs(L);//    LuaAnimal::Register(L);if (luaL_loadfile(L, "chenee.lua") || lua_pcall(L, 0, 0, 0)){        cout << "cannot run config. file:" << lua_tostring(L,-1) << endl;    }  lua_close(L);  return 0;}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.