* * * * *

                    99 ways to program a hex, Part 15: Lua

I'm still taking a break from C, and today's version is in Lua [1].

> #!/usr/bin/env lua
> -- ***************************************************************
> --
> -- Copyright 2012 by Sean Conner.  All Rights Reserved.
> --
> -- This program is free software: you can redistribute it and/or modify
> -- it under the terms of the GNU General Public License as published by
> -- the Free Software Foundation, either version 3 of the License, or
> -- (at your option) any later version.
> --
> -- This program is distributed in the hope that it will be useful,
> -- but WITHOUT ANY WARRANTY; without even the implied warranty of
> -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> -- GNU General Public License for more details.
> --
> -- You should have received a copy of the GNU General Public License
> -- along with this program.  If not, see <http://www.gnu.org/licenses/>.
> --
> -- Comments, questions and criticisms can be sent to: [email protected]
> --
> -- ********************************************************************
>
> -- Style: Lua 5.1
>
> function do_dump(fpin,fpout)
>   local offset = 0
>
>   while true do
>     local line = fpin:read(16)
>     if line == nil then return end
>       fpout:write(
>       string.format("%08X: ",offset),
>         line:gsub(".",function(c) return string.format("%02X ",c:byte()) end),
>       string.rep(" ",3 * (16 - line:len())),
>       line:gsub("%c","."),
>       "\n"
>       )
>     offset = offset + 16
>   end
> end
>
> -- **********************************************************************
>
> if #arg == 0 then
>   print("-----stdin-----")
>   do_dump(io.stdin,io.stdout)
> else
>   for i = 1 , #arg do
>     local f = io.open(arg[1],"r")
>     io.stdout:write("-----",arg[1],"-----","\n")
>     do_dump(f,io.stdout)
>     f:close()
>   end
> end
>
> os.exit(0)
>

What I'm noticing (besides my text editor's horrible attempts at syntax
highlighting in this entry) is that the non-C versions are quite a bit
shorter than the C versions. I'm sure part of that reason is the high level
of abstraction obtained by not using C. For instance, in this version, the
code to dump the data is easily half the length of the shortest C version
[2], thanks to the clever string.gsub() [3] routine in Lua.

* Part 14: COLOR COMPUTER BASIC [4]
* Part 16: Lua, recursion [5]

[1] http://www.lua.org/
[2] gopher://gopher.conman.org/0Phlog:2012/01/10.1
[3] http://www.lua.org/manual/5.1/manual.html#pdf-string.gsub
[4] gopher://gopher.conman.org/0Phlog:2012/01/22.1
[5] gopher://gopher.conman.org/0Phlog:2012/01/24.1

Email author at [email protected]