lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

This message is about Lua advocacy.

It just crossed my mind that in most programming languages
optimizations make code _less_ readable. In Lua, on the other hand, some
optimizations make code *MORE* readable.

For examples, we all know that access to local variables is
substantially faster that access to globals or table hashes. If I have to work with packet that contains a message represented by
an array of bytes an optimized way to use its content would be
something like this

local function parse(packet)
    local header   = packet.header
    local msg_begin= packet.msg[1]
    local msg_type = packet.msg[2]
    local dev_id   = packet.msg[3]..packet.msg[4]
    local coorX    = packet.msg[5]
    local coorY    = packet.msg[6]


Not only using local bindings to msg elements make the code run faster
(avoids repetitive packet.msg hash lookup) but, more importantly, such
code provides an explicit message format documentation. When the
message format changes, the code breaks. Fixing the broken code will
simultaneously update the documentation! How convenient.