loading a file iff it exists

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

Moderator: Forum Moderators

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

loading a file iff it exists

Post by melinath »

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
Art Contributor
Posts: 786
Joined: April 23rd, 2010, 8:17 pm
Location: Canada

Re: loading a file iff it exists

Post by Alarantalara »

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 »

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
Art Contributor
Posts: 786
Joined: April 23rd, 2010, 8:17 pm
Location: Canada

Re: loading a file iff it exists

Post by Alarantalara »

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