Showing the date in local format

Posted by Nick Gammon on Sat 24 Dec 2005 12:26 AM — 5 posts, 22,897 views.

Australia Forum Administrator #0
I noticed an interesting problem in Lua scripts while working on the Chat plugin.

The default for the locale seems to be the United States, because if you start MUSHclient (with Lua as the scripting language) and type:


/print (os.date ("%x"))  --> 12/24/05


Now this might seem OK if you live in the USA, however the date there is MM/DD/YY which is not what we use in Australia and other parts of the world.

In my case if I then type:


/print (os.setlocale ("", "time")) --> English_Australia.1252


Now it has set the locale to Australia. Now getting the date gives a different result:


/print (os.date ("%x"))  --> 24/12/05


This is now DD/MM/YY which is the local convention.

Thus scripters might want to consider putting:


os.setlocale ("", "time")


... at the start of Lua scripts (that display dates/times etc.) to set the locale correctly.
Australia Forum Administrator #1
Interestingly, once you do that once, it seems to set the locale for the entire executable, not just the current script environment.

For example, reloading the script retains the current locale.

Thus, it would be possible to make a tiny plugin that simply sets the locale, and does nothing else, as that would then affect every world and plugin.
USA #2
Donno if i should post this here but ya... I am nosey and wanted to test it out heh...

/print (os.date ("%x"))

Error number: 0
Event: Run-time error
Description: [string "Command line"]:1: attempt to index global `os' (a nil value)
stack traceback:
[string "Command line"]:1: in main chunk
Called by: Immediate execution

just wondering why that does that?
#3
Os calls in lua are disabled by default. You'll need to go to File > Global Preferences > Lua tab and enable it.
Australia Forum Administrator #4
Yes, in the Global Preferences, all calls to the os table are disabled by default.

You could uncomment the line:


os = nil


However, that removes the safety check it provides, by not allowing plugins to do things like remove files.

A safer approach is to save the "safe" functions, like this:


do
  local a, b, c, d, e = os.date, os.time, os.setlocale, os.clock, os.difftime
  os = {}  -- make new table
  os.date, os.time, os.setlocale, os.clock, os.difftime = a, b, c, d, e 
end


This basically saves the addresses of the harmless routines, creats a new "os" table, thus making the old one inaccessible, and then puts the old functions back into the new table.