Chapter 2. Calling C from Lua

C is the lingua franca of programming languages. Anything your system can do—such as access the internet, play an audio file, or generate real-time GPU-based 3D graphics—you can do via C code linked with the right libraries. Lua takes advantage of C’s universality by making it easy to share C functionality with Lua code. That’s what we’ll do in this chapter.

The example code in this chapter is split across two pairs of files. The first pair contains the files eatyguy1.c and eatyguy1.lua, whereas the second pair, in a rather predictable manner, contains the files eatyguy2.c and eatyguy2.lua. Thus continues the saga of the EatyGuy example code, which will grow iteratively throughout the remainder of this book, consistently with filenames that begin with eatyguy<num>. I hope this naming scheme makes it easier for you to see where each iteration fits into the big picture. It also reflects the typical iterative nature of software projects.

EatyGuy Version 1: A Lua-Callable C Function

Let’s begin by giving EatyGuy the ability to draw text characters with different background colors. We’ll write C code that creates the function listed in Table 2-1 in Lua.

Table 2-1. Description of the set_color() Lua function that we’ll implement in C
Lua function
set_color(<color_index>) Change the terminal’s current background color to <color_index>. Text printed out after this function is run will be printed with the given background color.

The tput Shell ...

Get Creating Solid APIs with Lua 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.