Example #1
0
int main(int argc, char *argv[]) {
  TEST_NAME();

  auto luaScript = LuaScript();

  luaScript.loadString("print('hello world!')");

  luaScript.loadScript("test.lua");

  luaScript.setGlobal("PI", 3.14);
  auto PI_value = luaScript.getGlobal_float("PI");

  TEST_EQUAL(PI_value, 3.14, "global - float");

  luaScript.setGlobal("numChildren", 3);

  auto numChildren = luaScript.getGlobal_int("numChildren");
  
  TEST_EQUAL(numChildren, 3, "global - int");

  luaScript.setGlobal("FirstName", "Benjamin Zaporzan");

  auto firstName = luaScript.getGlobal_string("FirstName");

  TEST_EQUAL(firstName, "Benjamin Zaporzan", "global - string");

  auto floatValues = floatArrayType {1.1, 2.2, 3.3};

  luaScript.setGlobal("Position", floatValues);
  luaScript.loadString("for i,v in ipairs(Position) do print(i,v) end");

  auto floatValues2 = luaScript.getGlobal_floatArray("Position");
  
  TEST_EQUAL(floatValues, floatValues2, "global - float array");

  for (auto i : floatValues2) {
    std::cout << i << std::endl;
  }

  auto intValues = intArrayType { 1, 2, 3 };

  luaScript.setGlobal("oneTwoThree", intValues);
  luaScript.loadString("for i,v in ipairs(oneTwoThree) do print(i,v) end");

  auto intValues2 = luaScript.getGlobal_intArray("oneTwoThree");

  TEST_EQUAL(intValues, intValues2, "global - int array");

  return 0;
}
Example #2
0
void GuiMedia::replaceMedia(string previousMedia, string type)
{
    auto scene = dynamic_pointer_cast<Scene>(_root.lock());

    // We get the list of all objects linked to previousMedia
    auto targetObjects = list<weak_ptr<BaseObject>>();
    for (auto& objIt : scene->_objects)
    {
        auto& object = objIt.second;
        if (!object->getSavable())
            continue;
        auto linkedObjects = object->getLinkedObjects();
        for (auto& linked : linkedObjects)
            if (linked->getName() == previousMedia)
                targetObjects.push_back(object);
    }

    Values msg;
    msg.push_back(previousMedia);
    msg.push_back(_mediaTypes[type]);
    for (const auto& weakObject : targetObjects)
    {
        if (weakObject.expired())
            continue;
        auto object = weakObject.lock();
        msg.push_back(object->getName());
    }

    setGlobal("replaceObject", msg);
}
StelShortcut::StelShortcut(const QString &id,
                           StelShortcutGroup* group,
                           const QString &text,
                           const QString &primaryKey,
                           const QString &altKey,
                           bool checkable,
                           bool autoRepeat,
                           bool global,
                           QGraphicsWidget *parent) :
    m_id(id), m_temporary(false)
{
	if (parent == NULL)
	{
		parent = StelMainGraphicsView::getInstance().getStelAppGraphicsWidget();
	}
	m_action = new QAction(parent);
	m_action->setObjectName(id);
	m_group = group;

	setText(text);
	setPrimaryKey(primaryKey);
	setAltKey(altKey);
	setCheckable(checkable);
	setAutoRepeat(autoRepeat);
	setGlobal(global);

	parent->addAction(m_action);
}
Example #4
0
void LuaInterface::registerSingletonClass(const std::string& className)
{
    newTable();
    pushValue();
    setGlobal(className);
    pop();
}
Example #5
0
cs8Variable::cs8Variable( QDomElement &element, const QString &description )
    : QObject()
{
    m_element = element;
    m_description = description;
    setBuildInTypes();
    setGlobal(false);
}
Example #6
0
HotkeyManager::HotkeyManager()
{
	/*
		枚举系统里面已经存在的Widget
	*/
	setGlobal(true);

	MyGUI::WidgetManager::getInstance().registerUnlinker(this);
}
Example #7
0
cs8Variable::cs8Variable()
    : QObject()
{
    m_docFragment = m_doc.createDocumentFragment();
    m_element = m_doc.createElement( "Data" );
    m_docFragment.appendChild( m_element );
    setBuildInTypes();
    setGlobal(false);
}
Example #8
0
void NAction::setGlobalShortcuts(const QList<QKeySequence> &shortcuts)
{
	setGlobal(FALSE);
	foreach (QKeySequence seq, shortcuts) {
		if (!seq.isEmpty()) {
			setGlobal(TRUE);
			break;
		}
	}

	foreach (QxtGlobalShortcut *shortcut, m_globalShortcuts)
		delete shortcut;
	m_globalShortcuts.clear();

	foreach (QKeySequence seq, shortcuts) {
		QxtGlobalShortcut *s = new QxtGlobalShortcut(this);
		connect(s, SIGNAL(activated()), this, SLOT(trigger()));
		s->setShortcut(seq);
		m_globalShortcuts << s;
	}
Example #9
0
Scene::Scene(Scene &scene)
{
    // We need to set the global constants to one when we duplicate a scene,
    // otherwise the global constants will be double counted (squared)
    CS123SceneGlobalData global = { 1, 1, 1, 1};
    setGlobal(global);

    // TODO [INTERSECT]
    // Make sure to copy over the lights and the scenegraph from the old scene,
    // as well as any other member variables your new scene will need.

}
Example #10
0
void LuaInterface::createLuaState()
{
    // creates lua state
    L = luaL_newstate();
    if(!L)
        g_logger.fatal("Unable to create lua state");

    // load lua standard libraries
    luaL_openlibs(L);

    // load bit32 lib for bitwise operations
    luaopen_bit32(L);

    // creates weak table
    newTable();
    newTable();
    pushString("v");
    setField("__mode");
    setMetatable();
    m_weakTableRef = ref();

    // installs script loader
    getGlobal("package");
    getField("loaders");
    pushCFunction(&LuaInterface::luaScriptLoader);
    rawSeti(5);
    pop(2);

    // replace dofile
    pushCFunction(&LuaInterface::lua_dofile);
    setGlobal("dofile");

    // dofiles
    pushCFunction(&LuaInterface::lua_dofiles);
    setGlobal("dofiles");

    // replace loadfile
    pushCFunction(&LuaInterface::lua_loadfile);
    setGlobal("loadfile");
}
int main() {
  char *key = malloc (4),
       *value = malloc (4);
  char *res;
  strncpy(key, "foo", 4);
  strncpy(value, "bar", 4);
 
  printf("test 1: init\n");
  initGlobals();
 
  printf("test 2: count\n");
  printf("\t%i\n",countGlobals());

  printf("test 3: write (%s, %s) ...\n", key, value);
  res=setGlobal(key, value);
  printf("\t...%s\n", res);

  printf("test 4: count\n");
  printf("\t%i\n",countGlobals());

  res=0;
  printf("test 5: read foo...\n");
  res=getGlobal(key);
  printf("\t...%s\n", res);

  res=0;
  printf("test 6: read other...\n");
  res=getGlobal("zip");
  printf("\t...%s\n", res);

  res=0;
  printf("test 7: remove other...\n");
  res=removeGlobal("zip");
  printf("\t...%s\n", res);

  printf("test 8: count\n");
  printf("\t%i\n",countGlobals());

  res=0;
  printf("test 9: remove foo...\n");
  res=removeGlobal("foo");
  printf("\t...%s\n", res);

  printf("test 10: count\n");
  printf("\t%i\n",countGlobals());

  printf("test 11: freeing\n");
  freeGlobals();

  return 0;
}
Example #12
0
int XHCPcmd_SETGLOBAL (int sockd, int argc, char **argv)
{
	if ( argc < 3 )
	{
		XHCP_printXHCPResponse (sockd, RES_SYNTAXERR );  // Syntax error
		return XHCP_EXE_ERROR;
	}

	if (  setGlobal(argv[1], argv[2]) == -1 )
            XHCP_printXHCPResponse (sockd, RES_INTNERROR); // Internal error
        else
            XHCP_printXHCPResponse (sockd, RES_GLOVALUPD); // "Global value updated"
        
	return XHCP_EXE_SUCCESS;
}
Example #13
0
void LuaInterface::evaluateExpression(const std::string& expression, const std::string& source)
{
    // evaluates the expression
    if(!expression.empty()) {
        std::string buffer = stdext::format("__exp = (%s)", expression);
        loadBuffer(buffer, source);
        safeCall();

        // gets the expression result
        getGlobal("__exp");

        // resets global __exp
        pushNil();
        setGlobal("__exp");
    } else
        pushNil();
}
Example #14
0
void LuaState::reload( unsigned int threadId )
{
    TRACE_ENTERLEAVE();
    
    if ( Leda::instance()->debug() && Leda::instance()->changes() > 0 )
    {
        if ( !m_lua )
        {
            throw std::runtime_error( "cannot reload without a loaded script first" );
        }
        
        TRACE("have %d filesystem changes, need to reload lua", Leda::instance()->changes() );
        destroy();
        create();
        loadlibs();
        load();
        setGlobal( "threadId", threadId );
        
        Leda::instance()->resetChanges();
    }
}
Example #15
0
void LuaInterface::loadFunction(const std::string& buffer, const std::string& source)
{
    if(buffer.empty()) {
        pushNil();
        return;
    }

    std::string buf;
    if(stdext::starts_with(buffer, "function"))
        buf = stdext::format("__func = %s", buffer);
    else
        buf = stdext::format("__func = function(self)\n%s\nend", buffer);

    loadBuffer(buf, source);
    safeCall();

    // get the function
    getGlobal("__func");

    // reset the global __func
    pushNil();
    setGlobal("__func");
}
Example #16
0
void LuaInterface::registerClass(const std::string& className, const std::string& baseClass)
{
    // creates the class table (that it's also the class methods table)
    newTable();
    pushValue();
    setGlobal(className);
    const int klass = getTop();

    // creates the class fieldmethods table
    newTable();
    pushValue();
    setGlobal(className + "_fieldmethods");
    int klass_fieldmethods = getTop();

    // creates the class metatable
    newTable();
    pushValue();
    setGlobal(className + "_mt");
    int klass_mt = getTop();

    // set metatable metamethods
    pushCppFunction(&LuaInterface::luaObjectGetEvent);
    setField("__index", klass_mt);
    pushCppFunction(&LuaInterface::luaObjectSetEvent);
    setField("__newindex", klass_mt);
    pushCppFunction(&LuaInterface::luaObjectEqualEvent);
    setField("__eq", klass_mt);
    pushCppFunction(&LuaInterface::luaObjectCollectEvent);
    setField("__gc", klass_mt);

    // set some fields that will be used later in metatable
    pushValue(klass);
    setField("methods", klass_mt);
    pushValue(klass_fieldmethods);
    setField("fieldmethods", klass_mt);

    // redirect methods and fieldmethods to the base class ones
    if(!className.empty() && className != "LuaObject") {
        // the following code is what create classes hierarchy for lua, by reproducing:
        // DerivedClass = { __index = BaseClass }
        // DerivedClass_fieldmethods = { __index = BaseClass_methods }

        // redirect the class methods to the base methods
        pushValue(klass);
        newTable();
        getGlobal(baseClass);
        setField("__index");
        setMetatable();
        pop();

        // redirect the class fieldmethods to the base fieldmethods
        pushValue(klass_fieldmethods);
        newTable();
        getGlobal(baseClass + "_fieldmethods");
        setField("__index");
        setMetatable();
        pop();
    }

    // pops klass, klass_mt, klass_fieldmethods
    pop(3);
}
Example #17
0
		static inline
		void registerConstructor(State* state, const std::string& name) {
			setGlobal(state, name, &construct_user_type<UserType, A...>);
		}
Example #18
0
 void LuaState::load( unsigned int threadId, bool exception, const char* init ) 
{
    TRACE_ENTERLEAVE();
    
    addPaths( "path" );
    addPaths( "cpath" );
    
    
    char script[ 1024 ];
    
    TRACE( "loading %s", m_filename.c_str() );
    setGlobal( "threadId", threadId );
    
    try
    {
        execute( "require 'leda'" );
        if ( init )
        {
            execute( init );
        }    
    }
    catch ( const  std::runtime_error& e )
    {
        if ( exception )
        {
            throw e;
        }
    }
    setArguments( );
    
    if ( m_filename.find( ".moon") != std::string::npos )
    {
        //
        //  moonscript
        //
        try
        {
            execute( "require 'moonscript'");
        }
        catch ( const std::runtime_error& e )
        {
            if ( exception )
            {
                throw e;
            }
            
            return;
        }
        
        sprintf( script, "local moonscript = require('moonscript'); "
        "moonscript.dofile('%s');", m_filename.c_str() ); 
    }
    else
    {
        //
        //  lua
        //
        sprintf( script,"dofile('%s');", m_filename.c_str() ); 
    }

    try
    {
        execute( script );
    }
    catch( const std::runtime_error& e )
    {
        if ( exception )
        {
            throw e;
        }
    }
    
   
   
}
Example #19
0
 void setValue(Token t, ValuePtr v)
 {
     std::string vname = t.value->toString();
     if (!setLocal(vname, v)) setGlobal(vname, v);
 }
Example #20
0
/* Return the package that an import is being performed in.  If globals comes
   from the module foo.bar.bat (not itself a package), this returns the
   sys.modules entry for foo.bar.  If globals is from a package's __init__.py,
   the package's entry in sys.modules is returned, as a borrowed reference.

   The *name* of the returned package is returned in buf.

   If globals doesn't come from a package or a module in a package, or a
   corresponding entry is not found in sys.modules, Py_None is returned.
*/
static Box* getParent(Box* globals, int level, std::string& buf) {
    int orig_level = level;

    if (globals == NULL || globals == None || level == 0)
        return None;

    static BoxedString* package_str = internStringImmortal("__package__");
    BoxedString* pkgname = static_cast<BoxedString*>(getFromGlobals(globals, package_str));
    if (pkgname != NULL && pkgname != None) {
        /* __package__ is set, so use it */
        if (pkgname->cls != str_cls) {
            raiseExcHelper(ValueError, "__package__ set to non-string");
        }
        size_t len = pkgname->size();
        if (len == 0) {
            if (level > 0) {
                raiseExcHelper(ValueError, "Attempted relative import in non-package");
            }
            return None;
        }
        if (len > PATH_MAX) {
            raiseExcHelper(ValueError, "Package name too long");
        }
        buf += pkgname->s();
    } else {
        static BoxedString* name_str = internStringImmortal("__name__");

        /* __package__ not set, so figure it out and set it */
        BoxedString* modname = static_cast<BoxedString*>(getFromGlobals(globals, name_str));
        if (modname == NULL || modname->cls != str_cls)
            return None;

        static BoxedString* path_str = internStringImmortal("__path__");
        Box* modpath = getFromGlobals(globals, path_str);

        if (modpath != NULL) {
            /* __path__ is set, so modname is already the package name */
            if (modname->size() > PATH_MAX) {
                raiseExcHelper(ValueError, "Module name too long");
            }
            buf += modname->s();
            setGlobal(globals, package_str, modname);
        } else {
            /* Normal module, so work out the package name if any */
            size_t lastdot = modname->s().rfind('.');
            if (lastdot == std::string::npos && level > 0) {
                raiseExcHelper(ValueError, "Attempted relative import in non-package");
            }
            if (lastdot == std::string::npos) {
                setGlobal(globals, package_str, None);
                return None;
            }
            if (lastdot >= PATH_MAX) {
                raiseExcHelper(ValueError, "Module name too long");
            }

            buf = std::string(modname->s(), 0, lastdot);
            setGlobal(globals, package_str, boxString(buf));
        }
    }

    size_t dot = buf.size() - 1;
    while (--level > 0) {
        dot = buf.rfind('.', dot);
        if (dot == std::string::npos) {
            raiseExcHelper(ValueError, "Attempted relative import beyond toplevel package");
        }
        dot--;
    }

    buf = std::string(buf, 0, dot + 1);

    BoxedDict* sys_modules = getSysModulesDict();
    Box* boxed_name = boxString(buf);
    Box* parent = sys_modules->d.find(boxed_name) != sys_modules->d.end() ? sys_modules->d[boxed_name] : NULL;
    if (parent == NULL) {
        if (orig_level < 1) {
            printf("Warning: Parent module '%.200s' not found "
                   "while handling absolute import\n",
                   buf.c_str());
        } else {
            raiseExcHelper(SystemError, "Parent module '%.200s' not loaded, "
                                        "cannot perform relative import",
                           buf.c_str());
        }
    }
    return parent;
    /* We expect, but can't guarantee, if parent != None, that:
       - parent.__name__ == buf
       - parent.__dict__ is globals
       If this is violated...  Who cares? */
}
Example #21
0
void LuaInterface::registerGlobalFunction(const std::string& functionName, const LuaCppFunction& function)
{
    pushCppFunction(function);
    setGlobal(functionName);
}
MarkerSection::MarkerSection(bool global) {
	setGlobal(global);
}
Example #23
0
void RobotManager::initRobotKs()
{
	setGlobal();
	initKSManager();
	updateKSManager();
}