Play With Lua!

Archive for May, 2015

Making a toy programming language in Lua, part 1

without comments

In this post, and the following posts in this series, I aim to fix something that’s bothered me for a while: writing a parser in Lua isn’t very approachable. In C you have the excellent chapter in The Unix Programming Environment (probably the best book on programming ever written) about how to use Lex and Yacc. For Ruby there’s the excellent Dhaka gem, as well as Racc, both of which work a lot like Yacc / Bison. There’s also Antlr, which seems to speak to every language except Lua.

Meanwhile Lua has LPeg, which is used nothing like Yacc, and tutorials are thin on the ground. So, I want to change that. This is going to be about how to make a toy programming language in Lua, in three parts. I’m going to loosely follow what the Lex / Yacc chapters of The Unix Programming Environment do, and we’ll end up with the same language.

Let’s begin.
Read the rest of this entry »

Written by randrews

May 29th, 2015 at 6:35 pm

Posted in Uncategorized

My Lua init file

without comments

I don’t think it’ll surprise anyone when I say that I think Lua is a great language. But, it does have a very small standard library. So, there are a few other utilities that I end up including or writing in almost everything I do. Luckily, Lua has a facility for loading them automatically when I open up the REPL.
Read the rest of this entry »

Written by randrews

May 22nd, 2015 at 12:00 pm

Posted in Uncategorized

Iterators

without comments

Lua doesn’t have a lot of control structures. There’s the obvious if statement, the while loop and repeat/until loop, and the for loop. Mostly, the for gets used to iterate over tables:

t = {'a','b','c','d','e'}
 
for i, v in ipairs(t) do
  print(i,t)
end

It’s annoying to have to remember to type ipairs every time. I’ve forgotten more than once. But, that minor annoyance is a good trade for the benefit of what the for statement actually does: generic iteration.
Read the rest of this entry »

Written by randrews

May 16th, 2015 at 12:25 am

Posted in Uncategorized

Telegrams

without comments

A few days ago at work, a friend of mine came up with this problem. I call it the “telegram” problem: you get a string consisting of words run together without spaces, and figure out where spaces can go to separate out the words. For example, a famous misunderstanding:

parse_telegram("turkeytrotstowaterwhereistaskforcethirtyfourtheworldwonders")
-- turkey trots to water where is task force thirty four the world wonders

I wrote a solution last night.

Read the rest of this entry »

Written by randrews

May 9th, 2015 at 1:24 am

Posted in Uncategorized