An unofficial, read-only Hacker News reader.

Lua for data representation (2025) (opens external site)

104 points by vinhnx 4 days ago | citrons.xyz | 61 comments on HN

View full thread · View on Hacker News

Comment thread (3)

  1. Interested in your lua book, is it available now?
    Replies (1)
    1. Yes! It’s public domain (especially the code examples), and here is the PDF:

      https://samboy.github.io/lunacy-book.pdf

      It’s a book for someone already familiar with any of AWK/Perl/Python who wants to use Lua mainly for text and regular expression parsing.

      The book covers a lot of bits of Lua which are easy to do in Perl/Python but hard to do in Lua. For example, here’s a Lua version of `deepcopy`:

        function deepcopy(orig, seen)
          if not seen then
            seen = {}
          end
          if type(orig) ~= "table" then
            return orig
          end
          local out = {}
          seen[orig] = out
          for k,v in pairs(orig) do
            if not seen[v] then
              out[k] = deepcopy(v, seen)
            else
              out[k] = seen[v]
            end
          end
          return out
        end
      
      Likewise, here’s Lua’s take on returning the keys of a table in order:

        -- This code is public domain
        -- Like pairs() but sorted
        function sPairs(inTable, sFunc)
          if not sFunc then
            sFunc = function(a, b)
              local ta = type(a)
              local tb = type(b)
              if(ta == tb) then
                if ta == 'number'
                  then return a < b
                end
                return tostring(a) <
                       tostring(b)
              end
              return ta < tb
            end
          end
          local keyList = {}
          local index = 1
          for k,_ in pairs(inTable) do
            table.insert(keyList,k)
          end
          table.sort(keyList, sFunc)
          return function()
            key = keyList[index]
            index = index + 1
            return key, inTable[key]
          end
        end
      
      And, finally, a lua version of `split` from Perl/Python:

        function split(s, splitOn)
          if not splitOn then splitOn = "," end
          local place = true
          local out = {}
          local mark
          local last = 1
          while place do
            place, mark = string.find(s, splitOn, last, false)
            if place then
              table.insert(out,string.sub(s, last, place - 1))
              last = mark + 1
            end
          end
          table.insert(out,string.sub(s, last, -1))
          return out
        end
      
      (All three of these functions are public domain)
      Replies (1)
      1. thanks, reading on my kindle now!