lua-users home
lua-l archive

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




On 2017-07-13 09:10 PM, Roberto Ierusalimschy wrote:
Almost… ^,^  The easiest way to understand C functions from Lua is that
they are always _vararg-only_ functions with no named parameters.  TNONE
doesn't exist on the Lua side (it's an artifact of indexing beyond top
of stack) but can be emulated by checking if the index is bigger than
`select('#',...)`.

So you can actually treat C functions as a feature-limited subset of Lua
functions, which is easy to understand.
Being vararg does not seem to be "feature-limited", quite the
opposite. We can think as if all functions in Lua were vararg. The
syntax

   function foo (a,b,c)

can be considered basically a sugar for

   function foo (...)  local a,b,c = ...

and, therefore, a restriction over a more permissive vararg handling.

The main difference between Lua functions and C functions is that C
functions do not have this sugar available, and so it is easier (and
more efficient, and maybe more natural) for them to work directly on the
varargs. (A near equivalent to this sugar in C would be to start the C
function with a lua_settop.)

-- Roberto



If functions had default values, NONE would be replaced with the given default values, while nil would be used as is. By using a sentinel value, it would be possible to tell none and nil apart without using select(). (e.g. in a sandbox)

local sentinel = {}

function foo(v, t=sentinel)
  if t == sentinel then
    error("table or nil expected, got none")
  end
  return setmetatable(v, t)
end

--
Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.