lua-users home
lua-l archive

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


It was thus said that the Great William Sumner once stated:
> Lua's behavior of silently returning nil for undefined variables can lead
> to bugs that propagate undetected. Has thought been given to changing this
> in a major version update, or are there reasons for retaining this
> behavior? I'm aware of strict.lua, but it only provides safety for
> global/module scope.

  As it has been mentioned elsewhere, the answer is "yes, the question has
been considered, and rejected."  But as someone who has cursed the more than
occasional typo in my own Lua code, I can see where this could be something
that is desirable, but I do have some questions.  

  1) What should be reported here?

	a = { roo = 5 }
	b = a.foo

  The intent here is for a field called 'foo' to exist.  The typo is in the
initialization for the table, not the reference.  Also, pretend that the two
statements are in different files.

  2) I have defined the following Lua function fork() (which calls the
system call fork())---it is defined as follows:

	static int proclua_fork(lua_State *const L)
	{
	  pid_t child;
	 
	  child = fork();
	  if (child > 0)
	  {
	    lua_pushinteger(L,child);
	    return 1;
	  }
	  else if (child == 0)
	  {
	    lua_pushinteger(L,0);
	    return 1;
	  }
	  else
	  {
	    lua_pushnil(L);
	    lua_pushinteger(L,errno);
	    return 2;
	  }
	}

And I call it thusly in Lua:

	proc = fork()
	if proc == nil then 
	  abort("program can't fork") 
	end

  What should fork() return to Lua to indicate an error?  Currently, I
return either <pid,0> or <nil,error>.  Here, nil encapsilates what I feel
happened---nothing was created, so nothing should be returned.  I suppose I
could return <-1,error> to get around this problem.

  3) Often times, I do this:

	function foo(a,b)
	  local a = a or "default value"
	  local b = b or "some other default value"
	end

  What should happen in this case?

	foo()

  Both a and b are nil, and thus, under your scheme, should throw an error,
right?

  In the end, you could always generate a custom build of Lua with the
behavior you want---the best place would be in lvm.c by modifying the
behavior of OP_GETUPVAL, OP_GETGLOBAL and OP_GETTABLE to generate an error
on reading a nil value and use that for Lua development.  If it's one thing
I've learned, is that working code and objective measurements (like number
of bugs caught for instance) tend to bolster a position.

  -spc (Half the time, I want to declare all my variables and table fields,
	the other half, I don't ... )