Delphi Wrapper for Lua

Lua is a the perfect language for extending Delphi applications by providing scripting capabilities. It is embeddable, compact and easily extended. Unlike other scripting languages, it provides control over access to operating system calls and the file system. Understanding the workings of the Lua API and putting it to use in a Delphi application does require some work. Our TLuaWrap class does most of this work. TLuaWrap has three properties

  • ErrCause: String – A text description of the reason why the last Lua exception was triggered.
  • LastError: :TLuaErrorTypes – An enumerated value indicating the nature of the last Lua exception.
  • Results: :TVariList – The TVariList class contains the entire set of return values from the last call to a method in a Lua script. Use the LVCount property to establish the number of return values available. Note that this can be greater than the number of return values specified in the Run method if one or more of the returns is a Lua table. Use the LVariants indexed property to access individual return values as variants.

Using TLuaWrap typically involves five steps

  • Use LoadScript to load a Lua script into the interpreter.
  • Now call the LocateCall method to specify the entry point method in that script. Naturally, the entry point method may in turn call other methods in the script, or indeed in other scripts loaded earlier.
  • With this done, specify all the parameters the entry point method requires in order to run. In Lua this is done by pushing values onto the Lua stack. Depending on the number and type of parameters you need to provide you will need to use the PushPushEx or PushTable methods.
  • You can now instruct the interpreter to execute the entry point method by invoking the Run method. Remember to provide the number of method parameters and return values as parameters to Run.
  • Barring errors in your code the method will execute and you will be able to examine its return values. Use the TLuaWrap.Results property for this purpose.
Usage: Create an instance of TLuaWrap – this is a wrapper around one instance of the Lua interpreter. Use TLuaWrap methods to load Lua scripts, select an entry function to call, pass parameters and retrieve results. The Lua documentation has extensive information on creating complex Lua scripts.