P. 1
Programming in LUA

Programming in LUA

4.8

|Views: 2,288|Likes:
Published by api-3733494

More info:

Published by: api-3733494 on Oct 15, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

03/18/2014

pdf

text

original

Suppose you want to list all identifiers used in a program source; somehow you
will need to filter the reserved words out of your listing. Some C programmers
could be tempted to represent the set of reserved words as an array of strings,
and then to search this array every time they need to know whether a given
word is in the set. To speed up the search, they could even use a binary tree or
a hash table to represent the set.
In Lua, a very efficient and simple way to represent such sets is to put the
set elements as indices in a table. Then, instead of searching the table for a
given element, you just index the table and test whether the result is nil or not.
In our example, we could write the next code:

reserved = {
["while"] = 1,
["end"] = 1,
["function"] = 1,
["local"] = 1,

}

if reserved[w] then
-- ‘w’ is a reserved word
...

(Because while is a reserved word in Lua, we cannot use it as an identifier. So,
we cannot write while = 1; instead, we use the ["while"] = 1 notation.)
You can have a clearer initialization using an auxiliary function to build the

set:

function Set (list)
local set = {}
for i=i,getn(list) do
set[list[i]] = 1

end
return set

end

reserved = Set{"while", "end", "function", "local", }

76

CHAPTER 11. DATA STRUCTURES

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->