Thursday, June 3, 2010

Differences between Kahlua2 and Lua 5.1

There are some noticable differences between Lua 5.1 and Kahlua2, and it may be good to know what they are.

Tables
Tables in Kahlua2 are implemented using a backing Hashtable or ConcurrentHashMap and as a result, implementing "next" properly would be inefficient and instead of implementing "next", it was removed. The function "pairs" still works, so use that instead. One common idiom using next in Lua 5.1 was checking if a table is empty:
function isempty(t) return next(t) == nil end


An alternative implementation of that in Kahlua2 would be:
function isempty(t) return pairs(t)() == nil end

but it would be inefficient, since it would create an iterator for each call to isempty.

Instead, you can use the method table.isempty(t) in Kahlua2.

Another side effect of using Java maps to implement tables, is that key equality is slightly different between Lua 5.1 and Kahlua2. In Lua 5.1, keys are equal in a table if they refer to the same object while in Kahlua2 they are equal if their hashcodes are equal and their equals()-methods return true. For strings, it works just as in Lua 5.1, but for numbers it's slightly different. Java treats -0 and +0 as different keys while Lua treats them as the same.

tostring
When converting things to strings in Kahlua2 (for example when calling tostring(obj)), it will not just return "userdata" if it doesn't have a better guess, it will instead use the toString() method for the object.

Weak tables
Kahlua2 doesn't support the __mode = "[k][v]" metatable magic to create weak tables. If you need weak tables, consider exposing a new method for creating a KahluaTable backed by a WeakHashMap or something similar.

Kahlua2 doesn't support the __gc feature for metatables, since there is no good way in Java to get notified when an object is about to get garbage collected. If you need this functionality, consider putting the object in a SoftReference to manually check when it's collected.

Libraries
Kahlua2 does not include any io or debug library. Some parts of the debug library may be added in the future, but the io library is better left added as a custom extension if necessary. The same thing goes for the os library, which is only partially implemented.

xpcall
Kahlua2 doesn't implement xpcall yet, but it might come in the future.

random and randomseed
random and randomseed in Lua uses a mutable global state, which is undesirable in Kahlua2.
Instead, use the following:
local myrandom = newrandom()
myrandom:random() -- real number in the range 0 to 1
myrandom:random(max) -- integer number in the range 1 to max
myrandom:random(min, max) -- integer number in the range min to max
myrandom:seed(obj) -- seeds the random instance with the hashcode of the object.

No comments:

Post a Comment