[JW Lua] Some Lua power

Jari Williamsson jari.williamsson at mailbox.swipnet.se
Sat Aug 31 13:02:34 CEST 2013


Hello all!

Virtually everything in the Lua language is based on tables with 
key/value pairs. This is one of the reasons why Lua is so easy to 
transform to proprietary language dialects. This is also why a R-value 
for a property might return nil, if it's undefined/misspelled (it's 
simply returning "the element doesn't exist in this table").

The table feature is extremely powerful in its simplicity, and it can 
simplify programming tasks quite a lot.

Here's an example on how to use it. The script below counts all the 
entries in the selected region, and collects the counters based on the 
staff the entry appears on.

If you have used some other computer language, you might notice that 
there's no need here to know in advance for how many staves the data 
should be collected, and the staff IDs doesn't even need to be in some 
specific order.

----
-- Collect the number of entries for each staff in
-- the selection in a Lua table
local staffstatistics = {}  -- Create an empty table
for e in eachentry(finenv.Region()) do
     if staffstatistics[e.Staff] == nil then
         staffstatistics[e.Staff] = 1
     else
         staffstatistics[e.Staff] = staffstatistics[e.Staff] + 1
     end
end

-- Print the collected statistics using Lua's pairs() iterator
-- "k" is the key, "v" is the value
for k, v in pairs(staffstatistics) do
     print ("Staff number", k, "has", v, "note entries")
end
----

(A key in the table can even be a string, so you could easily use Lua in 
a similar way to create a lyrics word counter, to find out how many 
times a certain word is used, for example.)

I'll perhaps put this example in the Wiki later on.


Best regards,

Jari Williamsson





More information about the JWLua mailing list