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 Josh Haberman once stated:
> I wanted to hear people's opinions about implicit conversion in Lua.
> 
> Say I am exposing to Lua a strongly-typed data structure. It behaves
> like a table in many ways, but the set of keys is predefined and each
> key as a pre-determined type. So for example:
> 
> -- Data structure is: name (string), age (integer)
> 
> struct.name = "James"
> struct.age = 22
> 
> -- Throws "no such field"
> struct.doesnt_exist = 5
> 
> -- Throws "can't assign string to integer field"
> struct.age = "XYZ"
> 
> So my first question is, does it seem Lua-like to allow implicit
> string <-> integer conversion when it is safe?
> 
> -- Auto-convert to "12345" or throw an error?
> struct.name = 12345
> 
> -- Auto-convert to 22 or throw an error?
> struct.age = "22"
> 
> Secondly, what is the Lua-like way to handle overflow and truncation?
> 
> -- Throw an error or truncate? (assume age is uint32_t)
> struct.age = <UINT32_MAX + 1>
> 
> -- Throw an error or silently truncate to 22?
> struct.age = 22.12345
> 
> It appears that luaL_checkinteger() in both Lua 5.2 and Lua 5.3 work1
> will silently truncate in this latter case.
> 
> Pros of auto conversion/truncation:
> - "do what I mean", less typing
> 
> Cons of auto conversion/truncation:
> - can lead to silent data loss/corruption
> - throwing errors might help find bugs sooner
> 
> Thoughts? What is the "Lua way" here?

  For

	struct.doesnt_exist = 5

I really don't do anything, since:

	x = struct.doesnt_exist

will return nil.  I suppose an argument could be made for triggering an
error on referencing 'struct.doesnt_exist' for debugging purposes.  

  As for

	struct.age = "123"

I tend not to do that, unless the quantity in question can be expressed in
different units.  For instance:

	struct.max_mem = 65536	-- use 64K

I would also allow the user to specify:

	struct.max_mem = '64k'	-- use 64k

to give some flexibility (also think time units).  

  As far as handling overflow and truncation, I haven't actually given it
much thought---I tend to be the only one that uses my code, and the code
that I have out there I've received no complaints so far.  

  -spc (Hmm ... I guess I tend to be pretty lax about this stuff ... )