lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]




On 16/06/15 05:42 PM, Brigham Toskin wrote:
On Mon, Jun 15, 2015 at 12:35 PM, Soni L. <fakedme@gmail.com> wrote:


On 15/06/15 03:16 PM, Sven Olsen wrote:
[It's a shame that declaring blocks that limit temporary variable
scope isn't more popular, perhaps the extra two lines and bonus
character in 'end' bothers OCD people like myself.

I've started writing do-blocks structured like the following:

  local draw_list do

    <other locals and definitions>

    draw_list= function() 
      <drawing code> 
    end
  end

The convention here is that the do block acts more or less like a 1 time function call who's purpose is to define the local(s) on the line where it starts. Feels like a useful pattern when I have a bunch of function definitions that all want their own copies of common variable names like 'x','y' etc.

-Sven
Bad on LuaJIT. If you're gonna do that I recommend you use (function(...) end)(...), e.g.

local draw_list = (function(...)
  <stuff>
  return function(list)
    <drawing code>
  end
end)(...) -- pass our chunk's vargs to the function

This lets LuaJIT know draw_list is a constant and make your code faster. (direct jump vs indirect jump)

I'm curious if you've actually dumped the traces to see this difference, or if you're assuming it will do this based on documentation or some other thread on the subject?
I'm assuming based on documentation/other thread, and also this: the opcodes indicate "local x do x = function() end end" loads "nil" into x, then changes x later, so LuaJIT can't just assume "x" is constant/immutable so instead it uses an indirect jump when you call x. with "local x = (function(...) return function() end end)(...)" there's a call opcode but x doesn't get implicitly nil-ed before it.

--
Brigham Toskin

-- 
Disclaimer: these emails are public and can be accessed from <TODO: get a non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.