Click here to Skip to main content
15,897,371 members
Articles / Containers / Virtual Machine

Integrating Lua into C++

Rate me:
Please Sign up or sign in to vote.
4.82/5 (42 votes)
2 Sep 2005CPOL8 min read 334.1K   8.6K   127  
An article about embedding the Lua scripting language with C++ objects.
// ---------------------------------------------------------------------------
// FILE NAME            : LuaThis.h
// ---------------------------------------------------------------------------
// DESCRIPTION :
//
// Controls the "this" table
// 
// ---------------------------------------------------------------------------
// VERSION              : 1.01
// DATE                 : 1-Sep-2005
// AUTHOR               : Richard Shephard
// ---------------------------------------------------------------------------
// LIBRARY INCLUDE FILES
#ifndef __LUA_THIS_H__
#define __LUA_THIS_H__

#include "lualib/luainc.h"
#include "luavirtualmachine.h"

// Sets the "this" global table that scripts use

class CLuaThis
{
public:
   CLuaThis (CLuaVirtualMachine& vm, int iRef) : m_iOldRef (0), m_vm (vm)
   {
      lua_State *state = (lua_State *) vm;
      if (vm.Ok ())
      {
         // Save the old "this" table
         lua_getglobal (state, "this");
         m_iOldRef = luaL_ref (state, LUA_REGISTRYINDEX);

         // replace it with our new one
         lua_rawgeti(state, LUA_REGISTRYINDEX, iRef);
         lua_setglobal (state, "this");
      }
   }

   virtual ~CLuaThis (void)
   {
      lua_State *state = (lua_State *) m_vm;
      if (m_iOldRef > 0 && m_vm.Ok ())
      {
         // Replace the old "this" table
         lua_rawgeti(state, LUA_REGISTRYINDEX, m_iOldRef);
         lua_setglobal (state, "this");
         luaL_unref (state, LUA_REGISTRYINDEX, m_iOldRef);
      }
   }


protected:
   int m_iOldRef;
   CLuaVirtualMachine& m_vm;
};

#endif // __LUA_THIS_H__

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions