<?xml version="1.0"?><rss version="2.0"><channel><title>Benaiah Mischenko</title><link>http://benaiah.me</link><description>RSS feed of Benaiah Mischenko's blog</description><item guid="benaiah.me:posts:everything-you-didnt-want-to-know-about-lua-multivals"><title>Everything You Didn’t Want to Know About Lua’s Multi-Values</title><link>https://benaiah.me/posts/everything-you-didnt-want-to-know-about-lua-multivals</link><pubDate>Mon, 4 May 2020 00:00:00 -0700</pubDate><description><![CDATA[<h1>Everything You Didn’t Want to Know About Lua’s Multi-Values</h1> 
 <p>I’ve been spending a lot of time lately writing <a href="https://fennel-lang.org">Fennel</a> and
contributing to its compiler. Since it’s a language that compiles to
Lua, that also means spending a lot of time getting to know Lua. This
article will be focused on Lua (though I’ll address Fennel from time
to time in the footnotes).</p> 
 <p>Lua is a neat, elegant, and relatively simple language. I find it
particularly notable for its embeddability into other programs;
capability of hosting many different styles of programming; and the
excellent performance of one of its implementations,
<a href="https://luajit.org/">LuaJIT</a>. In many ways, it feels like a more elegant and
restrained JavaScript - it supports tail call elimination<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> and
<a href="https://www.lua.org/pil/9.1.html">coroutines</a>, it doesn’t have the confusing <code>var</code>/<code>let</code>
distinction (though it lacked a feature like <code>const</code> until Lua 5.4),
and it doesn’t privilege class syntax over other styles of programming
(object oriented programming can be done in Lua with metatables, but
it’s not given special syntax like it is in JS).</p> 
 <p>That said, it has aspects that are undoubtedly quirky - arrays and
dictionaries are unified into "tables", whose integer indices start at
1; the standard library is unusually minimal, a nod to its
embeddability; it, like JavaScript, makes the immense error of making
variables global by default and local only when you ask. Curiously, it
also supports a quite uncommon language feature: multiple return
values (which we’ll call “multivals” for brevity’s sake). It is this
last subject that we’ll be unpacking more about today.</p> 
 <p>Since Lua is a dynamic language (as opposed to, say, Go) multiple
returns are implemented in a rather odd way. This isn’t explored in as
much detail as I’d like in Lua’s documentation, so I wanted to provide
a one-stop resource that explains everything I can think to write down
about this idiosyncratic part of the language.</p> 
 <p>A spoiler: unfortunately, multivals will turn out to be somewhat
underwhelming for use in code you care about. They’re awkward to work
with, have numerous gotchas, are a maintenance hazard, and don’t
perform notably better (that I know of) than their primary
alternative, tables. This is not a very <em>useful</em> article, unless you
have a use for knowing minutiae about Lua’s behavior.</p> 
 <p>Let’s dive in!</p> 
 <h2>An Introduction to Multivals - <code>1, 2, 3</code>, <code>unpack</code>, and <code>...</code></h2> 
 <p>There are three primary ways to represent a multival in Lua. Each of
these has their own distinct uses. Each of the following code snippets
produces the same multival:</p> 
 <ul>
<li>A multival literal: <code>1, 2, 3</code>. (Note that this does not include
table literals like <code>{1, 2, 3}</code>).</li>
<li>Unpacking a table: <code>table.unpack({1, 2, 3})</code></li>
<li>The vararg, <code>...</code>, in a function: <code>local function x(...) return ... end x(1, 2, 3)</code></li>
</ul> 
 <p>Multivals can be packed into a table by simply calling them:</p> 
 <pre><code class="language-lua">local function two_values() return "first", "second" end
local tab = {two_values()}
print(tab[1], tab[2])
  -- prints "first second"
</code></pre> 
 <p>To manipulate multivals, we can use two techniques: function
signatures and <code>select</code>:</p> 
 <pre><code class="language-lua">local function multival_first(x, ...) return x end
print(multival_first(1, 2, 3))
  -- prints "1"

local function multival_rest(x, ...) return ... end
print(multival_rest(1, 2, 3))
  -- prints "2 3"

print(select(2, 1, 2, 3))
  -- prints "2 3"; identical to the last line
</code></pre> 
 <p>In order to get values from the <em>end</em> of a multival, we have three
options. The first is recursion:</p> 
 <pre><code class="language-lua">local function increment_each_value(first, ...)
  if first then
    return first + 1, increment_each_value(...)
  end
end

print(increment_each_value(1, 2, 3))
  -- prints "2 3 4"
</code></pre> 
 <p>The second is packing the multival into a table. There are two ways to
do this, both of which are demonstrated below:</p> 
 <pre><code class="language-lua">-- 1. You can pack a multival directly into a table literal
local function pack_multival(...)
  return {...}
end

-- Lua's default printing for tables only shows identity; we'll just
-- print the length instead.
print(#pack_multival(1, 2, 3))
  -- prints "3"

-- 2. You can use table.pack, which is built in to Lua 5.2 and later
local tab = table.pack(1, 2, 3)

print(#tab)
  -- prints "3"

-- table.pack also sets the "n" field on the table it returns. This is
-- more efficient than using #tab, which iterates through the table.
print(tab.n)
  -- prints "3"
</code></pre> 
 <p>The final way of getting values from the end of a multival is <code>select</code>
combined with <code>select("#", ...)</code> (which we’ll dig into more later on):</p> 
 <pre><code class="language-lua">local function get_end_of_multival(...)
  local count = select('#', ...)
  return select(count, ...)
end

print(get_end_of_multival(1, 2, 3, 4, 5))
  -- prints "5"
</code></pre> 
 <h2>The Vararg: A Second-Class Value</h2> 
 <p>When you start working with multivals, they might seem pretty
straightforward. As long as you’re working on something that uses a
list with fixed length or that can be expressed by iterating through
the head and tail of a list, it seems like working with multivals
should be nice and predictable.</p> 
 <p>The first issue you’ll likely run into if you try to use multivals
heavily comes from expecting them to work the same way the rest of Lua
does. In short, Lua’s <code>local</code> variables use what’s called <em>lexical
scope</em>. This means that the scope of a variable definition is the
block of code that you see it contained in in your source code
file. It doesn’t matter what order other functions are called in, or
whether they’re called at all - the definitions of local variables can
be determined just by looking at the structure of the code. This is as
opposed to <em>dynamic scope</em>, where the variables defined at a given
point are dependent on the runtime of the program itself. Lua’s
<code>global</code> variables effectively use dynamic scope.</p> 
 <p>As discussed above, there’s only three ways to refer to a multival:
calling a function for its return values, literally inserting multiple
values separated by commas, or using the vararg symbol <code>...</code> as a
function argument. It’s this last case that we’re interested in.</p> 
 <p>When you use <code>...</code> in the signature of a function, you must place it
at the end of the argument list. (This is what prevents you -
syntactically, at least - from accessing the end of <code>...</code> without
either assigning the whole thing to individual variables, recursing
through it, or packing it into a table.)</p> 
 <p>You also can’t assign the whole thing to a variable, because assigning
a <code>...</code> to a variable means unpacking the multival and assigning the
<em>first value</em> to the variable - or multiple values, if that’s
specified. For example:</p> 
 <pre><code class="language-lua">-- Assigning the vararg to a single variable will assign that variable
-- to the _first value_ of the vararg.
local function try_to_assign_vararg(...)
  local x = ...
  return x
end

print(try_to_assign_vararg(1, 2, 3))
  -- prints "1"
</code></pre> 
 <p>There’s one additional rule about the vararg, however, that’s very
unlike the behavior of the rest of Lua. You can only use a vararg
<em>within the function where it is defined</em>. This prevents you from, for
instance, saving the vararg into a closure:</p> 
 <pre><code class="language-lua">local function try_to_return_vararg_from_closure(...)
  return function()
    return ...
  end
end
</code></pre> 
 <p>This fails to run with the following error: <code>cannot use '...' outside a vararg function near '...'</code>. This means that, while you can use
<code>...</code> in two nested functions, each <code>...</code> can only refer to the vararg
of the function that’s currently running. You can’t capture <code>...</code>
within a closure to persist it. Effectively, <code>...</code> is not lexically
scoped, but rather a dynamically scoped variable with certain extra
rules like not being reassignable and not being usable outside a
function that defined it.</p> 
 <p>Another way to put this would be to say that Lua’s multivals are
“second class” values. You might be familiar with languages that have
second class functions, which can’t be assigned to variables or passed
as a parameter to a functions. This is similar, with the notable
exception that we <em>can</em> pass the vararg to another function. We just
can’t save it in a variable, save it in a closure, or manipulate it in
certain ways.</p> 
 <h2>Cutoff Multivals</h2> 
 <p>Passing multivals to functions and packing them into tables is pretty
straightforward, but there’s one major gotcha about it we haven’t gone
over yet. Take a look at the following example:</p> 
 <pre><code class="language-lua">local function returns_three_values()
  return 1, 2, 3
end

print(returns_three_values())
  -- prints "1 2 3"
print(#{returns_three_values()})
  -- prints "3"

print(returns_three_values(), 4, 5)
  -- prints "1 4 5"
print(#{returns_three_values(), 4 5})
  -- prints "3"
</code></pre> 
 <p>As the second pair of <code>print</code> expressions demonstrates, a function
call can only return multiple values into a multival if it is the last
thing in the multival. Following a function call in a multival with
any other value, even <code>nil</code>, will cut off its return values at the
first item.</p> 
 <p>This also applies to the vararg, <code>...</code>, in function definitions:</p> 
 <pre><code class="language-lua">local function f(...)
  return ..., 4, 5
end

print(f(1, 2, 3))
  -- prints "1 4 5"
</code></pre> 
 <h2>Lua’s Most Jarring Feature: <code>select("#", ..)</code></h2> 
 <p>One of Lua’s nicer properties is how a key set to <code>nil</code> and a
non-existent key are indistinguishable in a table. In Javascript, for
instance, you have both <code>obj.x = undefined</code> to set a property to
<code>undefined</code> and <code>delete obj.x</code> to actually remove it from the
object. (There’s also <code>obj.x = null</code>, but let’s ignore that for now.)
In Lua, there’s just <code>tab.x = nil</code>, and there’s no way to distinguish
between a property that was set to <code>nil</code> and a property that was never
set at all.</p> 
 <p>With that in mind, let’s look at the following example:</p> 
 <pre><code class="language-lua">local y = {nil,nil,nil}

print(#y)
   -- prints "0" - nils at the end of a table don't matter

local function multival_length(...) select("#", ...) end

print(multival_length(table.unpack(y)))
  -- prints "0"

print(multival_length(nil, nil, nil))
  -- prints "3". wtf?
</code></pre> 
 <p>As this example demonstrates, multivals throw that nice property out
the window. Just to be clear:</p> 
 <ul>
<li>There is <em>no</em> distinction between <code>{nil, nil}</code> and <code>{}</code> in Lua.</li>
<li>There is <em>one</em> distinction between <code>multival_length(nil, nil)</code> and
<code>multival_length()</code> in Lua. That distinction is made by<code>select("#", ...)</code>.</li>
</ul> 
 <p>This becomes even more confusing when combined with a function that
returns <em>zero</em> values, as opposed to <code>nil</code>:</p> 
 <pre><code class="language-lua">print(select("#", print("a"), print("b"), print("c")))
  -- first prints each of "a", "b", and "c" on their own lines
  -- next, prints "2". wait, what?
</code></pre> 
 <p>What in the world? What’s going on here?</p> 
 <p>As it turns out, a function that returns zero values creates an empty
multival, as you’d expect. It also doesn’t add anything to the end of
a multival if you call it at the end. However, if a call to a
zero-return-value function appears <em>before</em> the end of a multival, it
results in a <code>nil</code> being inserted into the multival in place of its
zero return values. Thus, instead of collapsing the multival made up
of all three of the <code>print</code> calls into a single zero-length multival,
Lua instead collapses the <em>last</em> call to <code>print</code>, but turns the other
two calls into <code>nil</code>. This all doesn’t apply to tables, because,
unlike in multivals, <code>nil</code>s in tables are truly identical to absent
values.</p> 
 <p>At first, this all seems like something that doesn’t belong in
Lua. Without the <code>select("#", ...)</code> form, there’d be no way of telling
a <code>nil</code> at the end of a multival from the end of the multival
itself. However, this makes certain abstractions much easier to
create.</p> 
 <p>One notable situation where <code>select("#", ...)</code> becomes particularly
useful is when wrapping functions that return multiple
values. <code>select("#", ...)</code> lets you easily tell if you can simply save
the first return value from the function or if you need to create a
table to save all the values.</p> 
 <h2>Are You Sure That’s a Tail Call?</h2> 
 <p>When first looking at multivals in Lua, a programmer who’s determined
to use them somehow might first be inclined to combine them with tail
recursion to neatly express different functions. For instance, we
could implement <code>range</code> as follows:</p> 
 <pre><code class="language-lua">local function range1(acc, n)
  if n &lt; 1 then return
  elseif n == 1 then return acc
  else return acc, range1(acc+1, n-1)
  end
end

local function range(n)
  if n &lt; 1 then error("n must be &gt;= 1") end
  return range1(1, n)
end

print(range(3))
  -- prints "1 2 3"

print(#{range(10)})
  -- prints "10"
</code></pre> 
 <p>This works great! We can call <code>range(n)</code> when we want a multival of
length <code>n</code>, and surround it with braces like <code>{range(n)}</code> when we want
the equivalent table. This should let us avoid allocating extra tables
when we don’t need them. And since Lua has tail call elimination, the
recursive call <code>range1</code> makes to itself should never blow the
stack. Right?</p> 
 <pre><code class="language-lua">print(#{range(1000 * 1000)})
  -- throws a stack overflow error
</code></pre> 
 <p>Hmm.</p> 
 <p>As it turns out, multivals break tail call elimination. If you’re
returning multiple values, Lua needs to collect all those values
before it can actually begin to return them. This means that it can’t
throw away the stack frames of the recursing function. It’s very
similar to what would happen if you returned <code>{range1(acc, n)}</code> within
<code>range1</code>. That case is clearly <em>not</em> a tail call. It’s the particular
syntax of multivals that makes this confusing, since it doesn’t look
like the faux-tail-call is “surrounded” by anything.<sup class="footnote-ref"><a href="#fn2" id="fnref2">[2]</a></sup></p> 
 <p>In order to avoid the stack overflow and properly recurse the
function, we can implement <code>range</code> with a table as follows:</p> 
 <pre><code class="language-lua">local function range1(tab, acc, n)
  if n &lt; 1 then return tab
  else
    tab[acc] = acc
    return range1(tab, acc+1, n-1)
  end
end

local function range(n)
  if n &lt; 1 then error("n must be &gt;= 1") end
  return range1({}, 1, n)
end

print(#range(1000 * 1000))
  -- prints "1000000"
</code></pre> 
 <p>It’s perhaps less elegant, mixing recursion and mutation, but its
runtime characteristics are vastly better.</p> 
 <h2>Maximum Occupancy</h2> 
 <p>It makes sense that recursing to much could cause issues by blowing
the stack. What’s less intuitive is that multivals have a cap on their
size even when you make them <em>without</em> recursion. Consider this use of
the <code>range</code> function we defined above:</p> 
 <pre><code class="language-lua">local t = range(1000 * 1000)
print(t)
  -- prints a table identity
</code></pre> 
 <p>Great! Now, let’s try unpacking that into a multival. No recursion is
involved, so this should work fine, right?</p> 
 <pre><code class="language-lua">local t = range(1000 * 1000)
print(table.unpack(t))
  -- throws "too many results to unpack" error
</code></pre> 
 <p>As it turns out, multivals simply have a cap on the number of values
they can contain. There’s no way to work around this - if you need to
handle a list of items without worrying about how big it is, use a
table, not a multival.</p> 
 <p>Multival literals in function arguments and return values are even
more restricted:</p> 
 <pre><code class="language-lua">print((function() return 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
            14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
            28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
            42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
            56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
            70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
            84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
            98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
            110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120,
            121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131,
            132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
            143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
            154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
            165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
            176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186,
            187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197,
            198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208,
            209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
            220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230,
            231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
            242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252,
            253, 254, 255 end)())
  -- throws "function or expression needs too many registers" error

print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
      19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
      35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
      51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
      67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
      83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
      99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
      112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124,
      125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137,
      138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150,
      151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
      164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
      177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
      190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202,
      203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215,
      216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228,
      229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
      242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
      255)
  -- throws "function or expression needs too many registers" error
</code></pre> 
 <p>There is, however, no limit on table literals, reinforcing the fact
that the contents of table literals are not multivals, despite their
similarity in appearance:</p> 
 <pre><code class="language-lua">-- generate.lua
print("print(#{")
for i = 1, 1000 * 1000 do
    print(i ..",")
end
print("})")
</code></pre> 
 <pre><code class="language-bash">lua generate.lua &gt; generated.lua &amp;&amp; lua generated.lua
# prints "1000000"
</code></pre> 
 <h2>Multivals are Data Structures, Just Bad Ones</h2> 
 <p>What all these different examples of multival quirks demonstrate is
that multivals are just another data structure. (I find this case is
made best by how tail call elimination doesn’t work when recursing
within a multival, just like it wouldn’t work within a table literal.)
They aren’t exceptions to the rules that data structures follow - in
fact, they have <em>extra</em> rules that tables don’t. To sum up:</p> 
 <ul>
<li>Multivals cannot be assigned to variables. They can only referred to
as literals, function call expressions, or the vararg <code>...</code>.</li>
<li>The vararg cannot be used outside the function that creates it
(including within closures made within that function).</li>
<li>Multivals are cut off at the first value when inserting them into
another multival before its end.</li>
<li>Unlike tables, multivals have a built-in length that is unrelated to
the arrangement of <code>nil</code>s within the multival. This length can be
retrieved with <code>select("#", ...)</code>.</li>
<li>When a multival contains a call to a zero-return-value function
before the end of the multival, a <code>nil</code> is inserted where the
function’s return value would go.</li>
<li>When a function makes a recursive call within a multival, tail call
elimination is not applied. Recursing too many times within a
multival will thus blow the stack.</li>
<li>Unpacking too many values from a table into a multival will result
in an error.</li>
<li>Trying to call or return from a function with too many arguments
will result in an error. This limit is much lower than the
previously-mentioned limit on unpacking tables, being just below 255
items.</li>
</ul> 
 <h2>A Last Tiny Nitpick</h2> 
 <p>Finally, one incredibly subjective thing that bugs me about multivals
is the syntax used for the vararg. In my opinion, the fact that <code>...</code>
is valid Lua makes it unnecessarily hard to insert an
easily-understood placeholder into example code.</p> 
 <h2>Conclusion</h2> 
 <p>While multivals remain a strange and sharp-edged corner of Lua, I hope
that they’re a little bit easier to understand thanks to this
post. While they’re rarely the best solution to a given problem, it’s
still helpful for a Lua user to understand their strengths and
limitations, even if it’s only to justify avoiding them.</p> 
 <p><em>If you’d like to leave a comment, please email <a href="mailto:benaiah@mischenko.com">benaiah@mischenko.com</a></em></p> 
 <hr class="footnotes-sep"/> 
 <section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item"><p>Also known as Tail Call Optimization. JavaScriptCore, used in
Safari, has <a href="https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-in-webkit/">Proper Tail Call
Support</a>,
but most JS developers can’t make use of this, as it’s not
available in popular browsers on most platforms. <a href="#fnref1" class="footnote-backref">↩</a></p>
</li>
<li id="fn2" class="footnote-item"><p>In Fennel, this syntactical confusion gets even worse! There,
instead of having their own special syntax, multivals are
represented with the <code>values</code> special. <code>(values 1 2 3)</code> in Fennel
is the same as <code>1, 2, 3</code> in Lua. Unfortunately, this makes
recursive functions that run into this scenario look even <em>more</em>
like real tail-recursive functions. This is a gotcha to keep in
mind whenever working with multivals and recursion in Fennel! <a href="#fnref2" class="footnote-backref">↩</a></p>
</li>
</ol>
</section> 
]]></description></item><item guid="benaiah.me:posts:configuring-go-apps-with-toml"><title>Configuring Go Apps with TOML</title><link>https://benaiah.me/posts/configuring-go-apps-with-toml</link><pubDate>Mon, 13 Feb 2017 00:00:00 -0700</pubDate><description><![CDATA[<h1>Configuring Go Apps with TOML</h1> 
 <p>So you’ve been writing an application in Go, and you’re getting to the
point where you have a lot of different options in your program.
You’ll likely want a configuration file, as specifying every option on
the command-line can get difficult and clunky, and launching
applications from a desktop environment makes specifying options at
launch even more difficult.</p> 
 <p>This post will cover configuring Go apps using a simple, INI-like
configuration language called <a href="https://github.com/toml-lang/toml">TOML</a>, as well as some related
difficulties and pitfalls.</p> 
 <p>TOML has quite a few implementations, including several libraries for
Go. I particularly like
<a href="https://github.com/burntsushi/toml">BurntSushi’s TOML parser and decoder</a>, as it lets
you marshal a TOML file directly into a struct. This means your
configuration can be fully typed and you can easily do custom
conversions (such as parsing a <code>time.Duration</code>) as you read the
config, so you don’t have to do them in the rest of your application.</p> 
 <h2>Configuration location</h2> 
 <p>The first question you should ask when adding config files to any app
is "where should they go?". For tools that aren’t designed to be run
as a service, as root, or under a custom user (in other words, most of
them), you should be putting them in the user’s home directory, so
they’re easily changed. A few notes:</p> 
 <ul>
<li><p>Even if you currently have only one file, you should use a folder
and put the config file within it. That way, if and when you do need
other files there, you won’t have to clutter the user’s home
directory or deal with loading config files that could be in two
different locations (Emacs, for instance, supports both
<code>~/.emacs.d/init.el</code> and <code>~/.emacs</code> for historical reasons, which
ends up causing confusing problems when both exist).</p></li>
<li><p>You should name your configuration directory after your program.</p></li>
<li><p>You should typically prefix your config directory with a <code>.</code> (but
see the final note for Linux, as configuration directories within
<code>XDG_CONFIG_HOME</code> should not be so prefixed).</p></li>
<li><p>On most OSs, putting your configuration files in the user’s “home”
directory is typical. I recommend the library
<a href="https://github.com/mitchellh/go-homedir">go-homedir</a>, rather than the <code>User.Homedir</code> available
in the stdlib from <a href="https://golang.org/pkg/os/user/"><code>os/user</code></a>. This is because use of
<code>os/user</code> uses <a href="https://golang.org/cmd/cgo/">cgo</a>, which, while useful in many situations,
also <a href="https://dave.cheney.net/2016/01/18/cgo-is-not-go">causes a number of difficulties</a> that can
otherwise be avoided - most notably, cross-compilation is no longer
simple, and the ease of deploying a static Go binary gets a number
of caveats.</p></li>
<li><p>On Linux specifically, I strongly encourage that you do <em>not</em> put
your configuration directory directly in the user’s home directory.
Most commonly-used modern Linux distributions use the
<a href="https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html">XDG Base Directory Specification</a> from
<a href="https://www.freedesktop.org/wiki/">freedesktop.org</a>, which specifies standard locations
for various directories on an end-user Linux system. (Despite this,
many applications don’t respect the standard and put their
configurations directly in <code>~</code> anyway). By default, this is
<code>~/.config/</code>, but it can also be set with the <code>XDG_CONFIG_HOME</code>
environment variable. Directories within this should <em>not</em> use a
leading <code>.</code>, as the directory is already hidden by default.</p></li>
</ul> 
 <p>The following function should get you the correct location for your
config directory on all platforms (if there’s a platform with a
specific convention for config locations which I’ve missed, I’d
appreciate you letting me know so I can update the post - my email is
at the bottom of the page).</p> 
 <pre><code class="language-go">import (
    "path/filepath"
    "os"
    "runtime"

    "github.com/mitchellh/go-homedir"
)

var configDirName = "example"

func GetDefaultConfigDir() (string, error) {
    var configDirLocation string

    homeDir, err := homedir.Dir()
    if err != nil {
        return "", err
    }

    switch runtime.GOOS {
    case "linux":
        // Use the XDG_CONFIG_HOME variable if it is set, otherwise
        // $HOME/.config/example
        xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
        if xdgConfigHome != "" {
            configDirLocation = xdgConfigHome
        } else {
            configDirLocation = filepath.Join(homeDir, ".config", configDirName)
        }

    default:
        // On other platforms we just use $HOME/.example
        hiddenConfigDirName := "." + configDirName
        configDirLocation = filepath.Join(homeDir, hiddenConfigDirName)
    }

    return configDirLocation, nil
}
</code></pre> 
 <p>Within the config folder, you can use any filename you want for your
config - I suggest <code>config.toml</code>.</p> 
 <h2>Loading the config file</h2> 
 <p>To load a config file, you’ll first want to define the what config
values you’ll use. <code>burntsushi/toml</code> will ignore options in the TOML
file that you don’t use, so you don’t have to worry about that causing
errors. For instance, here’s the proposed configuration for a project
I’m maintaining, <a href="https://github.com/asciimoo/wuzz">wuzz</a> (the keybindings aren’t currently
implemented, but I’ve left them in for the sake of demonstration):</p> 
 <pre><code class="language-go">type Config struct {
    General GeneralOptions
    Keys    map[string]map[string]string
}

type GeneralOptions struct {
    FormatJSON             bool
    Insecure               bool
    PreserveScrollPosition bool
    DefaultURLScheme       string
}
</code></pre> 
 <p>It’s pretty simple. Note that we use a named struct for
<code>GeneralOptions</code>, rather than making <code>Config.General</code> an anonymous
struct. This makes nesting options simpler and aids tooling.</p> 
 <p>Loading the config is quite easy:</p> 
 <pre><code class="language-go">import (
    "errors"
    "os"
    
    "github.com/BurntSush/toml"
)

func LoadConfig(configFile string) (*Config, error) {
    if _, err := os.Stat(configFile); os.IsNotExist(err) {
        return nil, errors.New("Config file does not exist.")
    } else if err != nil {
        return nil, err
    }
    
    var conf Config
    if _, err := toml.DecodeFile(configFile, &amp;conf); err != nil {
        return nil, err
    }

    return &amp;conf, nil
}
</code></pre> 
 <p><code>toml.DecodeFile</code> will automatically populate <code>conf</code> with the values
set in the TOML file. (Note that we pass <code>&amp;conf</code> to <code>toml.DecodeFile</code>,
not <code>conf</code> - we need to populate the struct we actually have, not a
copy). Given the above <code>Config</code> type and the following TOML file…</p> 
 <pre><code class="language-text">[general]
defaultURLScheme = "https"
formatJSON = true
preserveScrollPosition = true
insecure = false

[keys]

  [keys.general]
  "C-j" = "next-view"
  "C-k" = "previous-view"
  
  [keys.response-view]
  "&lt;down&gt;" = "scroll-down"
</code></pre> 
 <p>…we’ll get a <code>Config</code> like the following:</p> 
 <pre><code class="language-go">Config{
    General: GeneralOptions{
        DefaultURLScheme:       "https",
        FormatJSON:             true,
        PreserveScrollPosition: true,
        Insecure:               false,
    },
    Keys: map[string]map[string]string{
        "general": map[string]string{
            "C-j": "next-view",
            "C-k": "previous-view",
        },
        "response-view": map[string]string{
            "&lt;down&gt;": "scroll-down",
        },
    },
}
</code></pre> 
 <h2>Automatically decoding values</h2> 
 <p><code>wuzz</code> actually uses another value in its config - a default HTTP
timeout. In this case, though, there’s no native TOML value that
cleanly maps to the type we want - a <code>time.Duration</code>. Fortunately, the
TOML library we’re using supports automatically decoding TOML values
into custom Go values. To do so, we’ll need a type that wraps
<code>time.Duration</code>:</p> 
 <pre><code class="language-go">type Duration struct {
    time.Duration
}
</code></pre> 
 <p>Next we’ll need to add an <code>UnmarshalText</code> method, so we satisfy the
<code>toml.TextUnmarshaler</code> interface. This will let <code>toml</code> know that we
expect a string value which will be passed into our <code>UnmarshalText</code>
method.</p> 
 <pre><code class="language-go">func (d *Duration) UnmarshalText(text []byte) error {
    var err error
    d.Duration, err = time.ParseDuration(string(text))
    return err
}
</code></pre> 
 <p>Finally, we’ll need to add it to our <code>Config</code> type. This will go in
<code>Config.General</code>, so we’ll add it to <code>GeneralOptions</code>:</p> 
 <pre><code class="language-go">type GeneralOptions struct {
    Timeout                Duration
    // ...
}
</code></pre> 
 <p>Now we can add it to our TOML file, and <code>toml.DecodeFile</code> will
automatically populate our struct with a <code>Duration</code> value!</p> 
 <p>Input:</p> 
 <pre><code class="language-text">[general]
timeout = "1m"
# ...
</code></pre> 
 <p>Equivalent output:</p> 
 <pre><code class="language-go">Config{
    General: GeneralOptions{
        Timeout: Duration{
            Duration: 1 * time.Minute
        },
        // ...
    }
}
</code></pre> 
 <h2>Default config values</h2> 
 <p>We now have configuration loading, and we’re even decoding a text
field to a custom Go type - we’re nearly finished! Next we’ll want to
specify defaults for the configuration. We want values specified in
the config to override our defaults. Fortunately, <code>toml</code> makes really
easy to do.</p> 
 <p>Remember how we passed in <code>&amp;conf</code> to <code>toml.DecodeFile</code>? That was an
empty <code>Config</code> struct - but we can also pass one with its values
pre-populated. <code>toml.DecodeFile</code> will set any values that exist in the
TOML file, and ignore the rest. First we’ll create the default values:</p> 
 <pre><code class="language-go">import (
    "time"
)
var DefaultConfig = Config{
    General: GeneralOptions{
        DefaultURLScheme:       "https",
        FormatJSON:             true,
        Insecure:               false,
        PreserveScrollPosition: true,
        Timeout: Duration{
            Duration: 1 * time.Minute,
        },
    },
    // You can omit stuff from the default config if you'd like - in
    // this case we don't specify Config.Keys
}
</code></pre> 
 <p>Next, we simply modify the <code>LoadConfig</code> function to use
<code>DefaultConfig</code>:</p> 
 <pre><code class="language-go">func LoadConfig(configFile string) (*Config, error) {
    if _, err := os.Stat(configFile); os.IsNotExist(err) {
        return nil, errors.New("Config file does not exist.")
    } else if err != nil {
        return nil, err
    }

    conf := DefaultConfig
    if _, err := toml.DecodeFile(configFile, &amp;conf); err != nil {
        return nil, err
    }

    return &amp;conf, nil
}
</code></pre> 
 <p>The important line here is <code>conf := DefaultConfig</code> - now when <code>conf</code>
is passed to <code>toml.DecodeFile</code> it will populate that.</p> 
 <h2>Summary</h2> 
 <p>I hope this post helped you! you should now be able to configure Go
apps using TOML with ease.</p> 
 <p>If this post was helpful to you, or you have comments or corrections,
please let me know! My email address is at the bottom of the page. I’m
also looking for work at the moment, so feel free to get in touch if
you’re looking for developers.</p> 
 <h2>Complete code</h2> 
 <pre><code class="language-go">package config

import (
    "errors"
    "path/filepath"
    "os"
    "runtime"
    "time"

    "github.com/BurntSushi/toml"
    "github.com/mitchellh/go-homedir"
)

var configDirName = "example"

func GetDefaultConfigDir() (string, error) {
    var configDirLocation string

    homeDir, err := homedir.Dir()
    if err != nil {
        return "", err
    }

    switch runtime.GOOS {
    case "linux":
        // Use the XDG_CONFIG_HOME variable if it is set, otherwise
        // $HOME/.config/example
        xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
        if xdgConfigHome != "" {
            configDirLocation = xdgConfigHome
        } else {
            configDirLocation = filepath.Join(homeDir, ".config", configDirName)
        }

    default:
        // On other platforms we just use $HOME/.example
        hiddenConfigDirName := "." + configDirName
        configDirLocation = filepath.Join(homeDir, hiddenConfigDirName)
    }

    return configDirLocation, nil
}

type Config struct {
    General GeneralOptions
    Keys    map[string]map[string]string
}

type GeneralOptions struct {
    DefaultURLScheme       string
    FormatJSON             bool
    Insecure               bool
    PreserveScrollPosition bool
    Timeout                Duration
}

type Duration struct {
    time.Duration
}

func (d *Duration) UnmarshalText(text []byte) error {
    var err error
    d.Duration, err = time.ParseDuration(string(text))
    return err
}

var DefaultConfig = Config{
    General: GeneralOptions{
        DefaultURLScheme:       "https",
        FormatJSON:             true,
        Insecure:               false,
        PreserveScrollPosition: true,
        Timeout: Duration{
            Duration: 1 * time.Minute,
        },
    },
}

func LoadConfig(configFile string) (*Config, error) {
    if _, err := os.Stat(configFile); os.IsNotExist(err) {
        return nil, errors.New("Config file does not exist.")
    } else if err != nil {
        return nil, err
    }

    conf := DefaultConfig
    if _, err := toml.DecodeFile(configFile, &amp;conf); err != nil {
        return nil, err
    }

    return &amp;conf, nil
}
</code></pre> 
 <p><em>If you’d like to leave a comment, please email <a href="mailto:benaiah@mischenko.com">benaiah@mischenko.com</a></em></p> 
]]></description></item><item guid="benaiah.me:posts:building-a-typescript-roguelike-part-1-tilemaps"><title>Building a TypeScript Roguelike, Part 1: Tilemaps</title><link>https://benaiah.me/posts/building-a-typescript-roguelike-part-1-tilemaps</link><pubDate>Thu, 8 Dec 2016 00:00:00 -0700</pubDate><description><![CDATA[<h1>Building a TypeScript Roguelike, Part 1: Tilemaps</h1> 
 <p>I’ve been meaning to learn <a href="https://www.typescriptlang.org/">TypeScript</a> for some time, so
I’ve decided to build a roguelike (or at least begin to build a
roguelike) in order to do some canvas programming as well.</p> 
 <p>This isn’t a guide, it’s a journal of my experiments, so follow at
your own risk. I can’t guarantee I’m going to make the best design
decisions right off the the bat.</p> 
 <p>I’ll be omitting most of the glue code from the articles, and I’m not
planning a writeup of the build system, but you can see the full
source code at the <a href="https://github.com/benaiah/typescript-roguelike/">GitHub repo</a>.</p> 
 <h2>Designing the tile data</h2> 
 <p>I want the game to be tile-based, so I’ll need some sort of generic tile
container for doing things like rendering the map, generating levels,
pathfinding, and so forth. For now, I’ll just represent the individual
levels as tiles:</p> 
 <pre><code class="language-typescript">// src/Tile.ts

enum Tile {
  Nothing = 0,
  Floor = 1
}
</code></pre> 
 <p>Eventually I’m planning on making this an object or bitmask that
stores additional information, but this will suffice for writing the
container.</p> 
 <h2>Row Major Ordering</h2> 
 <p>Tilemaps should be as simple as possible; I want to make them cheap
and reusable. The simplest way to store a grid of tiles would be an
array of rowsq, where a hypothetical <code>tileMap.at</code> function would look
like <code>(x, y) =&gt; this[y][x]</code>. This introduces a lot of overhead because
of all the arrays. Fortunately it’s quite easy to turn this into a
single array by arranging the elements like this:</p> 
 <pre><code class="language-typescript">const tileMap = [ 0, 0, 0, 0,
                  0, 0, 0, 0,
                  0, 0, 0, 0 ];
</code></pre> 
 <p>This is called a <a href="https://en.wikipedia.org/wiki/Row-_and_column-major_order"><em>row-major order</em></a>, and a <code>tiles.at</code>
function would look like <code>(width, x, y) =&gt; this[(y * width) + x]</code>.</p> 
 <p>I’d like to avoid tying higher-level code to this specific
representation, so I’ve abstracted the coordinate system in case I
want to swap it out. This is the code for a coordinate system:</p> 
 <pre><code class="language-typescript">// coords.ts

interface CoordinateSystem {
  getX(i: number): number;
  getY(i: number): number;
  getI(x: number, y: number): number;
}

class RowFirstCoordinates {
  public static GetX(i: number, width: number): number {
    return i % width;
  };
  public static GetY(i: number, width: number): number {
    return Math.floor(i / width);
  };
  public static GetI(x: number, y: number, width: number): number {
    return (y * width) + x;
  };

  // Instance methods allow you to store the width
  constructor(private width: number) { }
  public getX(i: number): number {
    return RowFirstCoordinates.GetX(i, this.width);
  }
  public getY(i: number): number {
    return RowFirstCoordinates.GetY(i, this.width);
  }
  public getI(x: number, y: number): number {
    return RowFirstCoordinates.GetI(x, y, this.width);
  }
}
</code></pre> 
 <p>This will allow us to convert in between coordinates and array
indices. Now I have everything I need to start building the
tilemaps.</p> 
 <h2>Designing the TileMap API</h2> 
 <p>I’d like tilemaps to have a <a href="fluentInterface">fluent interface</a>, but
one that avoids mutating existing references. Here’s an example of the
API I’m imagining:</p> 
 <pre><code class="language-typescript">const tiles = [ 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0,
                0, 0, 0, 0, 0,
                0, 0, 0, 0, 0,
                0, 0, 0, 0, 0 ];
const mapA = new TileMap(tiles, 5);

// Create a region with x, y, width, and height
const regionB = {
  x:     1, y:      1,
  width: 2, height: 2
};

// Design note: Since each change creates and returns a new TileMap,
// it would be ideal to be able to batch these into some sort of
// execution-plan object that could be applied all at once, for cases
// where I don't care about the intermediate states.
const mapB = mapA
  .fillRegion(regionB, 1)
  .setAt(0, 3, 2)
  .setAt(4, 3, 2);

mapB.tiles === [ 0, 0, 0, 2, 0,
                 0, 1, 1, 0, 0,
                 0, 1, 1, 0, 0,
                 0, 0, 0, 0, 2,
                 0, 0, 0, 0, 0 ];
</code></pre> 
 <p>For now, I’m just going to create and implement the following
interface, so I can get something on the screen:</p> 
 <pre><code class="language-typescript">// tileMaps.ts

import * as coords from "./coords";
import Tile from "./Tile";

// IRegion is used to represent an area without having to carry around
// a tile array.
interface IRegion {
  x: number;
  y: number;
  width: number;
  height: number;
}

type TileMapProcessor = { (tileMap: ITileMap): ITileMap }

interface ITileMap {
  width: number;
  height: number;
  tiles: Tile[];
  coords: coords.CoordinateSystem;
  getRegion: (region: IRegion) =&gt; ITileMap;
  fillRegion: (region: Iregion, contents: Tile) =&gt; ITileMap;
  applyProcessors: (processors: TileMapProcessor[]) =&gt; ITileMap;
}
</code></pre> 
 <p>You can see the beginnings of my desired interface in the signatures
of <code>getRegion</code>, <code>fillRegion</code>, and <code>applyProcessors</code> - they return
<code>TileMap</code>s so you can contine chaining operations. The methods do the
following:</p> 
 <ul>
<li><code>getRegion</code> takes an <code>IRegion</code> and returns an <code>ITileMap</code> containing
the size of that region, containing the tiles in that region.</li>
<li><code>fillRegion</code> takes an <code>IRegion</code> and a <code>Tile</code> and returns a new
<code>ITileMap</code> that is the result of setting all of the tiles in this
<code>ITileMap</code> to <code>contents</code>.</li>
<li><code>applyProcessors</code> takes a list of functions that transform an
<code>ITileMap</code> to another <code>ITileMap</code>. It passes this map through those
functions in the order given.</li>
</ul> 
 <p>The implementation for this is fairly straightforward:</p> 
 <pre><code class="language-typescript">// tileMaps.ts

import { assert, zeroedArray } from "./util"

class TileMap {
  public static NewEmpty(width: number, height: number) {
    const length = width * height;
    const tiles: Tile[] = zeroedArray(length);
    return new TileMap(tiles, width);
  }

  public readonly tiles: Tile[];
  public coords: coords.RowFirstCoordinates;
  public readonly height: number;
    public readonly width: number;
  constructor(tiles: Tile[], width: number) {
    assert(tiles.length % width === 0);
    this.width = width;
    this.height = tiles.length / width;
    this.coords = new coords.RowFirstCoordinates(width);
    this.tiles = tiles;
  }

  public getRegion(region: IRegion): TileMap {
    const { x, y, width, height } = region;
    assert((x + width &lt;= this.width) &amp;&amp; (y + height &lt;= this.height));
    const regionTiles = this.tiles.filter((tile, i) =&gt; {
      const tileX = this.coords.getX(i);
      const tileY = this.coords.getY(i);
      if ((tileX &gt;= x &amp;&amp; tileX &lt; x + width) &amp;&amp; (tileY &gt;= y &amp;&amp; tileY &lt; y + height)) {
        return true;
      } else {
        return false;
      }
    });

    return new TileMap(regionTiles, width);
  }
  public fillRegion(region: IRegion, contents: number): TileMap {
    const { x, y, width, height } = region;
    assert((x + width &lt;= this.width) &amp;&amp; (y + height &lt;= this.height));
    const newTiles = this.tiles.map((tile, i) =&gt; {
      const tileX = this.coords.getX(i);
      const tileY = this.coords.getY(i);
      if ((tileX &gt;= x &amp;&amp; tileX &lt; x + width) &amp;&amp; (tileY &gt;= y &amp;&amp; tileY &lt; y + height)) {
        return contents;
      } else {
        return tile;
      }
    });

    return new TileMap(newTiles, this.width);
  }
  public applyProcessors(processors: TileMapProcessor[]): ITileMap {
    return processors.reduce((map, processor) =&gt; processor(map), this as ITileMap);
  }
}
</code></pre> 
 <p>I’ll make another type to represent renderers, and then I can move on
to actually drawing something</p> 
 <pre><code class="language-typescript">// tileMaps.ts

type TileMapRenderer = { (tileMap: ITileMap): void };
</code></pre> 
 <h2>Drawing a map</h2> 
 <p>Finally, I’m ready to draw my first map. First I’ll get the canvas and
create a game loop:</p> 
 <pre><code class="language-typescript">// main.ts

import * as tileMaps from "./tileMaps";

const canvas = &lt;HTMLCanvasElement&gt;document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Nothing's changing yet, so I only need to draw once
let drawn = false;
let time;

const gameLoop = (ctx: CanvasRenderingContext2D,
                  map: tileMaps.ITileMap,
                  renderer: tileMaps.TileMapRenderer) =&gt; {
  const now = new Date().getTime();
  const dt = now - (time || now);
  time = now;

  console.log(dt);

  const recurse = (delta) =&gt; gameLoop(delta, ctx, map, drawer);
  if (!rendered) {
    renderer(map);
    rendered = true;
  }
  requestAnimationFrame(recurse);
};
</code></pre> 
 <p>Now I just need a map and a renderer. I’ll generate a map with some
simple rooms:</p> 
 <pre><code class="language-typescript">// main.ts

class Room extends tileMaps.TileMap {
  public readonly x;
  public readonly y;
  constructor(public readonly parent: tileMaps.ITileMap, region: tileMaps.IRegion) {
    super(parent.getRegion(region).tiles, region.width);

    this.x = region.x;
    this.y = region.y;
  }
}

function getRandomRooms(tileMap: tileMaps.ITileMap): Room[] {
  return zeroedArray(getRandomInt(3, 9)).map(() =&gt; {
    const width = getRandomInt(10, 20);
    const height = getRandomInt(10, 20);
    const x = getRandomInt(0, tileMap.width - width);
    const y = getRandomInt(0, tileMap.height - height);
    return new Room(tileMap, { x, y, width, height });
  });
}

function createRooms(tileMap: tileMaps.ITileMap): tileMaps.ITileMap {
  const rooms = getRandomRooms(tileMap, 10);

  return rooms.reduce(
    (map, room) =&gt; map.fillRegion(room, Tile.Floor), tileMap);
}

const mapCreationLayers = [
  createRooms,
];
</code></pre> 
 <p>You’ll notice the signature of createRooms:
<code>(tileMap: tileMaps.ITileMap): tileMaps.ITileMap</code>. That’s the same
type for which I defined the alias <code>tileMaps.TileMapProcessor</code> -
meaning I can create an empty map and pass it through
<code>mapCreationLayers</code> as follows:</p> 
 <pre><code class="language-typescript">// main.ts

const mapWidth = 120;
const mapHeight = 80;

const map = tileMaps.TileMap.NewEmpty(mapWidth, mapHeight)
  .applyProcessors(mapCreationLayers);
</code></pre> 
 <p>And finally, I write a function to render the tiles to the canvas:</p> 
 <pre><code class="language-typescript">// main.ts

const render = (tileMap: tileMaps.ITileMap) =&gt; {
  tileMap.tiles.map((tile, i) =&gt; {
    const x = map.coords.getX(i);
    const y = map.coords.getY(i);
    ctx.fillStyle = (tile === Tile.Floor) ? "#FFF" : "#000";
    ctx.fillRect(x * tileWidth, y * tileHeight, 10, 10);
  });
};
</code></pre> 
 <p>Eventually the tile colors will be drawn with a pixel buffer which is
scaled up to the full size of the canvas, making drawing a grid of
solid colors much faster. At the moment, however, I’m only rendering
the map once - in the starting frame.</p> 
 <p>It’s all set - I can now kick off the game loop to start it off:</p> 
 <pre><code class="language-typescript">// main.ts

gameLoop(ctx, map, render);
</code></pre> 
 <!-- <img src="/assets/typescript-roguelike-screenshot-1.png"> --> 
 <p>Doesn’t look like much, but it’s a success! In the next post I’ll be
adding more types of tiles and exploring ways to generate a level. You
can also check out the <a href="https://github.com/benaiah/typescript-roguelike/">GitHub repo</a>, or try a running version at
<a href="http://roguelike.benaiah.me">roguelike.benaiah.me</a>.</p> 
 <p><em>If you’d like to leave a comment, please email <a href="mailto:benaiah@mischenko.com">benaiah@mischenko.com</a></em></p> 
 <div class="post-github-repo">
  <a href="http://github.com/benaiah/typescript-roguelike/">
    <span class="github-image"><img src="/assets/github.png"/></span>
    <span class="link-text">Visit the <strong>Github Repo</strong></span>
  </a>
</div> 
]]></description></item><item guid="benaiah.me:posts:using-ido-emacs-completion"><title>Using ido for Emacs completion</title><link>https://benaiah.me/posts/using-ido-emacs-completion</link><pubDate>Fri, 14 Oct 2016 00:00:00 -0700</pubDate><description><![CDATA[<h1>Using ido for Emacs completion</h1> 
 <h2>Update</h2> 
 <div class="post-date">March 22, 2020</div> 
 <p>At some point, <code>ido-hacks</code> became no longer required, and
<code>ido-ubiquitous</code> was folded into another package -
<code>ido-completing-read+</code>. I’ve also somewhat modified my config since I
wrote this post. Here’s the ido config I’m using today:</p> 
 <pre><code class="language-emacs-lisp">(use-package ido :quelpa
  :config
  (setq ido-everywhere t
    ido-virtual-buffers t
    ido-use-faces t
    ido-default-buffer-method 'selected-window
    ido-auto-merge-work-directories-length -1)
  (ido-mode))
(use-package flx-ido :quelpa :requires ido :config (flx-ido-mode))
(use-package ido-vertical-mode :quelpa :requires ido :config (ido-vertical-mode))
(use-package ido-completing-read+ :quelpa :requires ido
  :config
  (setq ido-ubiquitous-max-items 50000
    ido-cr+-max-items 50000)
  (ido-ubiquitous-mode +1))
</code></pre> 
 <p>If you’re wondering what the <code>:quelpa</code> keyword means or what it does,
see my other post <a href="/posts/bootstrapping-emacs-config-quelpa-use-package/">“Bootstrapping an Emacs config with
quelpa-use-package”</a>.</p> 
 <h2>Original post</h2> 
 <hr/> 
 <p>I’m a heavy user of <a href="ido">ido</a> – it handles all of my completion,
whether <code>execute-extended-command</code>, <code>find-file</code>, or whatever else.
However, ido’s default configuration leaves much to be desired:</p> 
 <ul>
<li>The way it displays results by default is quite difficult to read,
as you can’t quickly skip your eyes to the next item when they’re
all listed in a single wrapped line.</li>
<li>The default completion is prefix-only</li>
<li>It’s not obvious how to make ido actually complete <em>everything</em></li>
</ul> 
 <p>Fortunately this is all quite fixable with a few packages and a little
configuration:</p> 
 <ul>
<li><code>ido-everywhere</code>, when set to <code>t</code>, puts ido in more places than the
default.</li>
<li><code>ido-virtual-buffers</code> doesn’t <em>fix</em> anything per se, but it does add
recentf files to <code>find-file</code> completion, which is really handy.</li>
<li><a href="https://github.com/creichert/ido-vertical-mode.el">ido-vertical-mode</a> makes ido display each result
on its own line, with a configurable amount of lines to display at a
time (though I just use the default).</li>
<li><a href="https://github.com/lewang/flx/blob/master/flx-ido.el">flx-ido</a> fixes the completion by using the <a href="https://github.com/lewang/flx">flx</a>
completion engine.</li>
<li><a href="https://github.com/scottjad/ido-hacks">ido-hacks</a> and <a href="https://github.com/DarwinAwardWinner/ido-ubiquitous">ido-ubiquitous</a> together
make ido complete everything I’ve wanted so far.</li>
</ul> 
 <p>My full ido configuration is as follows:</p> 
 <pre><code class="language-emacs-lisp">(use-package ido :quelpa :config
  (setq ido-auto-merge-delay-time 99999999)
  (setq ido-everywhere t)
  (setq ido-virtual-buffers t)
  (ido-mode))
(use-package flx-ido :quelpa :requires ido :config (flx-ido-mode))
(use-package ido-vertical-mode :quelpa :requires ido :config (ido-vertical-mode))
(use-package ido-hacks :quelpa (:stable nil) :requires ido :config (ido-hacks-mode))
(use-package ido-ubiquitous :quelpa :requires ido :config (ido-ubiquitous-mode))
</code></pre> 
 <p>Enjoy!</p> 
 <p><em>If you’d like to leave a comment, please email <a href="mailto:benaiah@mischenko.com">benaiah@mischenko.com</a></em></p> 
]]></description></item><item guid="benaiah.me:posts:bootstrapping-emacs-config-quelpa-use-package"><title>Bootstrapping an Emacs config with quelpa-use-package</title><link>https://benaiah.me/posts/bootstrapping-emacs-config-quelpa-use-package</link><pubDate>Thu, 13 Oct 2016 00:00:00 -0700</pubDate><description><![CDATA[<h1>Bootstrapping an Emacs config with quelpa-use-package</h1> 
 <p>Emacs configuration is already a hairy enough beast as it is, but
package management introduces a whole new set of confusing, difficult
problems. What I want from an Emacs package management system is the
following:</p> 
 <ul>
<li>Every package I use should be recorded in my config</li>
<li>My init file should ensure all my packages are installed when I
start emacs.</li>
<li>If any packages are not installed, the init should automatically
download and install them.</li>
<li>MELPA Stable should be used, not MELPA, unless I specify that a
package should be installed from regular MELPA (for packages that
don’t have a stable version).</li>
<li>I don’t want to have to manually trigger package updates.</li>
</ul> 
 <p>It’s a fairly simple set of requirements, but for a long time it was
all-but-impossible to impossible to actually get all of them with
Emacs’ packaging functionality. Fortunately a couple projects have
come out that allow this vision to become a reality:</p> 
 <ul>
<li><a href="https://github.com/jwiegley/use-package">use-package</a> allows you to specify your packages in
your init and keep their configuration isolated and tidy.</li>
<li><a href="https://github.com/quelpa/quelpa">quelpa</a> allows you to build Emacs packages directly from
source, using MELPA recipes. It also allows you to default to MELPA
Stable, only using MELPA when specified.</li>
<li><a href="https://github.com/quelpa/quelpa-use-package">quelpa-use-package</a> combines the two, allowing
you to specify how a package should be installed as part of its
use-package declaration.</li>
</ul> 
 <p>I’ve created a minimal example of how to use these three packages
together in such a way that you don’t need <em>anything</em> installed except
for Emacs and the <code>init.el</code>. Once you start Emacs, everything will be
automatically installed for you. You can find that at
<a href="https://github.com/benaiah/quelpa-use-package-bootstrap-config">quelpa-use-package-bootstrap-config</a>. Please note that I
haven’t tested this with any versions of Emacs prior to 25.1.1 (the
version I’m currently running), nor on Windows, but I expect it should
work as far back as 24.3.1 or 24.4, and there’s no OS-specific code in
the init.</p> 
 <p>Some caveats:</p> 
 <ul>
<li>You do have to pay attention to your packages and their
dependencies. Some packages require you to grab other packages
explicitly before they will work. In addition, MELPA packages that
come from <a href="http://emacswiki.org?interface=en">EmacsWiki</a> usually
fail to build on my machine, so I rehost the wiki packages I need to
GitHub and install them like so:
<pre><code class="language-emacs-lisp">(use-package goto-chg :quelpa
  (goto-chg :stable nil :fetcher github :repo "benaiah/goto-chg"))
</code></pre></li>
<li>If you’re not on a network and you don’t have your packages
installed, this won’t work.</li>
<li>While I’m writing this, no MELPA Stable version of
quelpa-use-package exists, so you do technically have at least one
unstable dependency with this setup. However, quelpa-use-package
currently works well, and is rarely updated.</li>
</ul> 
 <p>This setup has been working very well for me, and I hope it will be
useful to you as well. It’s solid, easy to use (once you have it set
up), and should theoretically make it trivial to set up Emacs on a new
computer.</p> 
 <p><em>If you’d like to leave a comment, please email <a href="mailto:benaiah@mischenko.com">benaiah@mischenko.com</a></em></p> 
 <div class="post-github-repo">
  <a href="https://github.com/Benaiah/quelpa-use-package-bootstrap-config">
    <span class="github-image"><img src="/assets/github.png"/></span>
    <span class="link-text">Visit the <strong>Github Repo</strong></span>
  </a>
</div> 
]]></description></item><item guid="benaiah.me:posts:watching-filesystem-racket"><title>Watching the Filesystem in Racket</title><link>https://benaiah.me/posts/watching-filesystem-racket</link><pubDate>Mon, 10 Oct 2016 00:00:00 -0700</pubDate><description><![CDATA[<h1>Watching the Filesystem in Racket</h1> 
 <h2>Update - changed the tool used and watch code</h2> 
 <div class="post-date">February 10, 2017</div> 
 <p>Originally, this post used a tool called
<a href="https://github.com/emcrisostomo/fswatch">fswatch</a> to monitor the file
system. Unfortunately, <code>fswatch</code> has
<a href="https://github.com/emcrisostomo/fswatch/issues/134">a bug</a> on some Linux
systems where it detects file <em>reads</em> as file <em>changes</em>.  The bug has
gone unaddressed for several months. It causes a lot of problems - in
my static site generator, the <code>-w</code> option will build once and wait for
an event fine, but as soon as it sees a change it will start building
the site over and over again without any changes, as it detects the
generator reading the source files and triggers a new build, which
repeats ad infinitum.</p> 
 <p>I’ve thus replaced the tool used for monitoring directory changes with
<a href="https://github.com/mattgreen/watchexec">watchexec</a>, a similar tool,
also cross-platform, written in Rust. While I haven’t been able to
test this on platforms other than Linux, it doesn’t have any known
bugs of that variety, and <code>fswatch</code>'s bug made it completely unusable
on what has become my primary platform.</p> 
 <h2>Updated Post</h2> 
 <hr/> 
 <p>I’ve been building a new site lately, which will likely be inaugurated
with this very post. My tech decisions for the site are a whole post
of their own, but suffice it to say I’m using a static site generator
I wrote in <a href="https://racket-lang.org/">Racket</a>, and it’s going
swimmingly.</p> 
 <p>As I’m working on both the generator and the site at the same time,
most of the time I have a pain point while writing I can fix it
myself. (This is not necessarily a good thing, as I’d likely get more
writing done if I wasn’t spending so much time on the generator). One
of the biggest things I want out of the generator is live file
watching, so when I change files it automatically updates the site.</p> 
 <p>There aren’t any existing libraries that I could find for watching a
filesystem for changes, but this presented an opportunity to learn how
to implement an oft-used pattern of mine: shelling out.</p> 
 <p>You see, there’s a cross-platform, <em>very simple</em> file change monitor
called <a href="https://github.com/mattgreen/watchexec">watchexec</a>. Simple as
in "given a directory (searched recursively), whenever a file is
changed, run a command". Simple is particularly nice in this case
because it means it will be easy to interpret the output – all I need
to do is figure out how to watch a path.</p> 
 <h2>Spawning the process</h2> 
 <p>Looking at the documentation for <a href="https://docs.racket-lang.org/reference/subprocess.html#%27def._%28%28lib._racket%2Fsystem..rkt%29._process%29%29">process</a>, it appears
that we can spawn a process and get its input and output ports<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup>.
Let’s write a function that will let us watch a list of paths (this
requires <code>racket/string</code> and <code>racket/system</code>):</p> 
 <pre><code class="language-scheme">;; `watch' requires that the `watchexec' command is installed.
(define (watch-paths paths)
  (let ((paths-string
         (string-join
          (map (lambda (path)
                 ;; Quote paths to avoid escaping problems
                 (string-append
                  "-w \""
                  ;; Accept either strings or path objects
                  (cond [(string? path) path]
                        [(path? path) (path-&gt;string path)]
                        [else ""])
                  "\" "))
               paths)
          " ")))
    (process (string-append
              "watchexec " paths-string "-- echo \"File changed.\""))))
</code></pre> 
 <p>We can run <code>watchexec</code> at the command line to check the output[^2]:</p> 
 <pre><code class="language-sh">$ watchexec -w ~/dev/personal-site -- echo "File changed."
File changed.
File changed.
</code></pre> 
 <p>Now we need to kick off a build when the watch tools produces output.
Fortunately Racket makes it very easy to call a callback when a port
produces output, using <a href="https://docs.racket-lang.org/reference/sync.html#%28def._%28%28quote._~23~25kernel%29._handle-evt%29%29">handle-evt</a>. It’s as simple as
<code>(handle-evt &lt;event object&gt; &lt;event handler)</code>. We do need to explicitly
create a loop and a channel we can use to break from it, as well.</p> 
 <pre><code class="language-scheme">(define (watch site-directory)
  (letrec (;; Start the watch process
           (watcher (watch-paths (list (build-path site-directory "src"))))

           ;; This is the port we use to read the watch tool's output
           (watcher-output (list-ref watcher 0))

           ;; Putting a message to this channel allows us to exit the
           ;; watch loop programatically
           (exit-channel (make-channel))

           ;; `process' requires that its IO ports are manually
           ;; closed, so we do so in the exit channel's handler
           (exit-handler
            (lambda (val)
              (close-input-port watcher-output)
              (close-output-port (list-ref watcher 1))))

           ;; This function handles the events fired by the watcher
           ;; output port
           (input-handler
            (lambda (val)
              (let ((output (read-line watcher-output)))
                (cond
                 ;; If the watch tool stops, we'll get an EOF in the
                 ;; port. When this happens we need to quit
                 [(eof-object? output)
                  (channel-put exit-channel 'done)
                  (loop "")]
                 [else (loop output)]))))

           ;; This is the function that will loop and wait for events
           (loop
            (lambda ([files "No"])

              ;; We don't want to build the site when exiting, where
              ;; we'll be passed an empty string
              (and (not (string=? files ""))
                   ;; Build the site
                   (displayln "")
                   (displayln (string-append files " files changed, rebuilding..."))
                   (build site-directory)
                   (displayln "Built!"))

              ;; `sync' waits for either the input port or the exit
              ;; channel to send an event
              (sync (handle-evt watcher-output input-handler)
                    (handle-evt exit-channel exit-handler))))

           ;; Kick off the loop
           (watch-thread (thread (lambda () (loop)))))

    ;; Callers may need to be able to access both the thread (so they
    ;; can wait on it if necessary), and the exit channel (so they can
    ;; programatically stop the loop).
    `((thread . ,watch-thread)
      (exit-ch . ,exit-channel))))
</code></pre> 
 <h2>Watching from the command line</h2> 
 <p>We’re almost done! At this point we can call <code>(watch &lt;site-directory&gt;)</code> and it will call the <code>build</code> function every time
a file changes. However, we’d rather be able to do this without having
to enter the Racket REPL every time.</p> 
 <p>Fortunately creating a command line wrapper for this function is quite
easy. All we need to do is create a new file with no <code>.rkt</code> extension
and put a hashbang line that points to the racket executable at the
top:</p> 
 <pre><code class="language-scheme">#!/usr/local/bin/racket
#lang racket

(require "build.rkt")

(define watch? (make-parameter #f))

(define args
  (command-line
   #:once-each
   [("-w") "watch" (watch? #t)]
   #:args
   (str) str))

(if (watch?)
    (let ((watcher (watch args)))
      (thread-wait (dict-ref watcher 'thread)))
    (build args))
</code></pre> 
 <p>The <code>thread-wait</code> waits for the loop thread we spawn before exiting
the process. Without this, the script would exit immediately, which
defeats the purpose.</p> 
 <p><em>If you’d like to leave a comment, please email <a href="mailto:benaiah@mischenko.com">benaiah@mischenko.com</a></em></p> 
 <hr class="footnotes-sep"/> 
 <section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item"><p>If you’re not familiar with ports in the Scheme family, they’re essentially data queues that have a first-class representation. <a href="#fnref1" class="footnote-backref">↩</a></p>
</li>
</ol>
</section> 
]]></description></item></channel></rss>