Chapter 13. Interfacing Lua with Other Languages

Lua has a flexible mechanism for binding to program elements written in languages other than Lua. As you saw in the preceding chapter, functions in libraries written in C can be made available to your Lua programs through Lua's C application programming interface (C API or simply API). In this chapter, you delve a little deeper into this interface and learn the basics of writing routines in C that can be used in conjunction with Lua. This includes the following:

  • Embedding Lua in an application

  • Extending Lua with C functions

  • Manipulating the virtual stack in C

  • Passing values between Lua and C

  • Storing Lua values in C

  • Guarding against errors in your C code

  • Structuring the binding layer

Although the focus in this chapter is the C programming language, most mainstream implementations of compiled languages like C++ and Pascal are compatible with the C calling convention — these languages work fine with Lua. In this chapter, references to C programs and libraries are intended to include those that are written in other compatible languages as well.

If you are unfamiliar with C, take a moment to skim through some of the C examples. It should provide ample grounds for appreciating the clean, readable syntax of Lua.

How C Programs Use Lua

Lua's C API can be used both by a host application that embeds Lua and by libraries that extend Lua. The distinction between these two ways of using Lua can be blurred somewhat because a host application often provides ...

Get Beginning Lua Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.