Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Bradley Smith

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Lua: string interpolation


   1  
   2  ---
   3  -- Interpolates values into a string.
   4  --
   5  -- Values are encoded in the form %(key,format)
   6  -- where key is the index into the values table
   7  -- and format is the string.format option without
   8  -- the % character.
   9  --
  10  -- @param s the string into which values are inserted
  11  -- @param tab the table of values for lookup
  12  -- @return
  13  function interp(s, tab)
  14    return (s:gsub('%%%((%a[^,]*),([-0-9%.]*[cdeEfgGiouxXsq])%)',
  15              function(k, fmt)
  16                local f = loadstring("return " .. k)
  17                setfenv(f, tab)
  18                value = f()
  19                return value and ("%"..fmt):format(value) or '%('..k..')'..fmt
  20              end))
  21  end
  22  
  23  -- Sets interpolation for the '%' operator on strings
  24  getmetatable("").__mod = interp
  25  
  26  -- Example
  27  t = {key = "concentration", val = {56.2795, 1.2}}
  28  print( "%(key,s) is %(val[2],7.2f)%" % t )
  29  
  30  

Lua: unpack multiple tables

The standard unpack function only operates on one table. The following snippet will unpack elements from any number of tables.

   1  
   2  ---
   3  -- Returns all elements from all table arguments
   4  function unpacks( ... )
   5    local values = {}
   6  
   7    -- Collect values from all tables
   8    for i = 1, select( '#', ... ) do
   9      for _, value in ipairs( select( i, ... ) ) do
  10        values[ #values + 1] = value
  11      end
  12    end
  13  
  14    return unpack( values )
  15  end
  16  
  17  x = {'a', 'b', 'c', 'd', 'e'}
  18  y = {'v', 'w', 'x', 'y', 'z'}
  19  print( unpacks( x, y ) )
  20  
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS