This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.
Programming in Lua | ||
Part IV. The C API Chapter 28. User-Defined Types in C |
In the previous chapter, we saw how to extend Lua with new functions written in C. Now, we will see how to extend Lua with new types written in C. We will start with a small example that we will extend through the chapter with metamethods and other goodies.
Our example is a quite simple type: numeric arrays. The main motivation for this example is that it does not involve complex algorithms, so we can concentrate on API issues. Despite its simplicity, this type is useful for some applications. Usually, we do not need external arrays in Lua; hash tables do the job quite well. But hash tables can be memory-hungry for huge arrays, as for each entry they must store a generic value, a link address, plus some extra space to grow. A straight implementation in C, where we store the numeric values without any extra space, uses less than 50% of the memory used by a hash table.
We will represent our arrays with the following structure:
typedef struct NumArray { int size; double values[1]; /* variable part */ } NumArray;We declare the array
values
with size 1 only as a placeholder,
because C does not allow an array with size 0;
we will define the actual size by the space we allocate for the array.
For an array with n
elements,
we need sizeof(NumArray) + (n-1)*sizeof(double)
bytes.
(We subtract one from n
because the original structure already
includes space for one element.)
Copyright © 2003–2004 Roberto Ierusalimschy. All rights reserved. |