loading a file iff it exists

Discussion of Lua and LuaWML support, development, and ideas.

Moderators: Forum Moderators, Developers

Post Reply
User avatar
melinath
Posts: 1298
Joined: May 20th, 2009, 7:42 am

loading a file iff it exists

Post by melinath » March 26th, 2011, 7:21 pm

Does anyone happen to know a technique for loading a file iff it exists? I've tried:

Code: Select all

pcall(wesnoth.require("blah.lua"))
but the "file does not exist" error still propagates and halts my code.

User avatar
Alarantalara
macOS Packager
Posts: 782
Joined: April 23rd, 2010, 8:17 pm
Location: Canada

Re: loading a file iff it exists

Post by Alarantalara » March 26th, 2011, 8:24 pm

pcall doesn't work that way, which is why you're having the problem. It needs a function as an argument to execute, not the result of the execution.

Staying with pcall, the correct way to use it is:

Code: Select all

pcall(function () wesnoth.require("blah.lua") end)
I've used an anonymous function to minimize the space taken, but the point is that you pass the name of a function but do not call it yourself. This means the function must have 0 arguments.

User avatar
melinath
Posts: 1298
Joined: May 20th, 2009, 7:42 am

Re: loading a file iff it exists

Post by melinath » March 26th, 2011, 9:35 pm

Hah... of course. Thanks. I swear I read the docs... :-p

Incidentally, though, pcall can take a function with args[1]. This is what I'm doing now (which works):

Code: Select all

pcall(wesnoth.require, "blah.lua")
[1] http://www.lua.org/manual/5.1/manual.html#pdf-pcall

User avatar
Alarantalara
macOS Packager
Posts: 782
Joined: April 23rd, 2010, 8:17 pm
Location: Canada

Re: loading a file iff it exists

Post by Alarantalara » March 26th, 2011, 9:38 pm

And now I've learned that pcall has variable argument lists. Excellent.

Post Reply