# Palomino - Lua module

©2004,2009 Jim E. Brooks http://www.palomino3d.org

- Index
- Overview
- Lua/C++ Binding Reference
- Lua Execution
- Lua Class
- C++ Classes as Lua Objects
- Lua Scripts

## Overview

[2008/10]

See also Lua Scripts.

The Lua interpreter is integrated with the simulator's source code. The simulator has a set of C functions to interface with Lua scripts.

The lua module consists of:

    src/lua_lang/  # the Lua interpreter
    src/lua_bind/  # the simulator's C interface for Lua scripts
    scripts/       # Lua scripts (*.lua files)

### Design Rule: C++ shouldn't depend on scripting

A design rule is that the C++ simulator core should be written to be neutral of any scripting language.

In practice, the C++ core is integrated with a Lua interpreter. Although, in general, the C++ core doesn't call Lua functions, C++ has to call Lua functions to startup Lua and broadcast timer-ticks and the DestroyObject Event.

## Lua/C++ Binding Reference

[2008/05]

See the lua_bind namespace in doxygen.

## Lua Execution

[2008/05]

The Lua interpreter stores its state in a `lua_State` struct. This means that every time the simulator's C++ code calls Lua and Lua returns back, Lua remembers all of its objects, global vars, etc.

The C++ simulator calls Lua at certain points:

- Lua::Startup()scripts/startup.lua
- Lua::Tick()scripts/tick.lua

In turn, Lua can call a set of C functions exported to Lua by the C++ simulator.

## Lua Class

[2008/05]

This C++ class abstracts the Lua interpreter. Lua::RunScript() has the ability to cache bytecode in case the same Lua script is re-executed [reference].

## C++ Classes as Lua Objects

[2008/05]

To avoid C++ new/delete problems, instances of C++ classes are created as reference-counted pointers (osg::Referenced). C++ classes are exported to Lua as metatables. The "__gc" method is called by Lua's garbage-collector. __gc() is implemented by a C function that calls ref_ptr::unref() to decrement the reference-count. C++ delete is not called explicitly thus avoiding problems if the simulator or OSG is still using a C++ object. This is implemented by allocating a Lua "userdata" object. Then C++ "placement new" is used to construct an osg::ref_ptr at that memory location.

Last modified: Sat Nov 7 14:53:42 CST 2009