lua-users home
lua-l archive

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

On 11/03/2014 19.13, Luiz Henrique de Figueiredo wrote:
Consider this scheme instead of a chain of ifs:

local handlers={
	["abc"]=function (prefix,info) ... end,
	["123"]=function (prefix,info) ... end,

local badprefix=function (prefix,info) error("cannot handle "..prefix) end

while true do
	local prefix, info = line:sub(1,3), line:sub(4)
	local h = handlers[prefix] or badprefix

In case the embedded system could not tolerate many string allocations, an alternative could be to build an integer out of the numeric value of the first three characters, such as (untested):

 local a, b, c = string.byte(s, 1, 3)
 local id = (65536 * a) + (256 * b) + c

then use 'id' as index in a table, or for direct comparison.