Search code examples
objectprologexistslogtalk

Check if object already exists?


i have :

:- use_module(library(logtalk)).
:- {buffer}.
:- initialization(main).

main :-
    create_object(env,[instantiates(buffer)],[],[]), 

it works but every time I re-consult the file it barks an error because the object already exists.

Is there a way to check if the object already exists and skip recreating it ?


more code:

:- use_module(library(logtalk)).

:- consult(utils).

%% :- initialization((
%%     logtalk_load([buffer,env]).
%% )).
:- {buffer}.
:- initialization(main).

main :-
    %% create_object(env,[instantiates(buffer)],[],[]), 
    env::set(uid,0), env::set(name,"").

this worked :

:- initialization((
    logtalk_load([buffer])
)).

i.e. no dot and no "env"


Solution

  • You can use the current_object/1 predicate to check if an object exists. But from your code fragment is seems that you could simply define the env object in a source file. If you need env to be a dynamic object (why?), then use the dynamic/0 directive:

    :- object(env,
        instantiates(buffer)).
    
        :- (dynamic)/0.
    
    :- end_object
    

    Btw, never use top-level abbreviations (such as {}/1) in source files; they are not part of the language. Write instead:

    :- use_module(library(logtalk)).
    :- initialization((
        logtalk_load([buffer, env])
    )).
    

    P.S. You're using the logtalk pack for SWI-Prolog. But this pack meant for deployment, not development, as it hides all files on the Logtalk distribution (including documentation) inside the hidden directory used for packs.