[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: implicit conversions in Lua -- what is idiomatic?
- From: Josh Haberman <jhaberman@...>
- Date: Sun, 5 Jan 2014 22:55:24 -0800
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?