Break is broken?

I’ve recently started playing with SilverBullet and Lua and have found an oddity with looping that appears to be a bug; specifically, when breaking from a key, value loop, it sometimes causes an error.

Here’s a starting code block that works:

      ${(function()
        local fruits = {"apple", "banana", "cherry"}
        local result = {}
        for index, fruit in ipairs(fruits) do
          table.insert(result, fruit)
        end
        return result
      end)()}
      
      - apple
      - banana
      - cherry

Now add a break. Instead of returning just the first item, it returns an error:

      ${(function()
        local fruits = {"apple", "banana", "cherry"}
        local result = {}
        for index, fruit in ipairs(fruits) do
          table.insert(result, fruit)
          break  -- leave with first fruit
        end
        return result
      end)()}
      
      Lua error:

Oddly, if you add more code, the error goes away:

      ${(function()
        local fruits = {"apple", "banana", "cherry"}
        local result = {}
        for index, fruit in ipairs(fruits) do
          table.insert(result, fruit)
          local foo = {}  -- it doesn't seem to matter what else you do here
          break
        end
        return result
      end)()}
      
      - apple

Incremental loops don’t appear to have this problem:

      ${(function()
        local fruits = {"apple", "banana", "cherry"}
        local result = {}
        for i = 1, #fruits do  -- switch to incremental loop
          table.insert(result, fruits[i])
          break
        end
        return result
      end)()}
      
      - apple

Is there some Lua convention that I’m missing here, or is this just a bug in SB or Lua?

You hit a bug in our Lua implementation, I just fixed it here: Lua: fix `break` edge case · silverbulletmd/silverbullet@cb0c741 · GitHub

Thanks for reporting!

2 Likes