The Lua Pragramming Language: It's Cool
Geoff Richards
geoff@laxan.com
Features
- Very simple
- Very expressive
- Easy to extend
- Relatively easy C/C++ integration
- Super fast register-based VM
- Ideal for
- Embedded scripting language
- Calling C libraries
Types
nil, true, false
- Numbers
- Strings
- Tables (for arrays and hashes)
- C objects and pointers (userdata, lightuserdata)
Syntax: variables
local foo = "stuff"
foo = "other stuff"
print(foo)
Syntax: tables as arrays
local t = { "foo", "bar", "baz" }
print(t[1])
for idx, value in ipairs(t) do
print("item number " .. idx ..
" is " .. value)
end
Syntax: tables as hashes
local t = {
foo = "string value",
bar = 23,
["foo bar"] = "not identifier",
}
print(t.foo)
print(t["foo bar"])
for key, value in pairs(t) do
print("key " .. key ..
" is " .. value)
end
Syntax: functions
function sum (x, y)
return x + y
end
print(sum(2, 3))
Syntax: closures
function make_counter ()
local count = 0
return function ()
count = count + 1
return count
end
end
local counter = make_counter()
print(counter())
print(counter())
print(make_counter()())
Syntax: using modules
local Filter = require "datafilter"
print(Filter.base64_decode("Zm9vYmFy"))
Syntax: defining modules
local M = { _NAME = "simplemaths" }
function M.sum (x, y) return x + y end
function M.mul (x, y) return x * y end
return M
OO features
- Not many
- Metatables allow simple single-inheritance
- More complicated stuff possible, but best avoided
- Special method syntax using
:
OO example
local Widget = {}
Widget.__index = Widget
function Widget.new (class, num)
local self = { num = num }
setmetatable(self, class)
return self
end
function Widget:description ()
return "widget number " .. self.num
end
local mywidget = Widget:new(23)
print(mywidget:description())
Other non-features
- Pure ANSI C (almost), small codebase
- Separate int and float types
- Mutable strings (use memoryfile module)
- Standard library
- Regular expressions (simpler patterns instead)
Calling C
- Simple stack-based API
- Can't hold pointers to Lua values
C function example
static int
my_getenv (lua_State *L) {
const char *name = luaL_checkstring(L, 1);
const char *value = getenv(name);
if (value)
lua_pushstring(L, value);
else
lua_pushnil(L);
return 1;
}
Embedding in applications
- Used in games, Adobe Lightroom
- All access through lua_State objects
- Each Lua state can be in a thread
- Easy to call Lua functions