86 lines
1.9 KiB
C++
86 lines
1.9 KiB
C++
#ifndef DLANG_LIBS_LIST_HPP
|
|
#define DLANG_LIBS_LIST_HPP
|
|
|
|
#include <chrono>
|
|
#include <thread>
|
|
#include "../vm.hpp"
|
|
#include "../helpers.hpp"
|
|
|
|
void NativeListInsert(DlangVM* vm)
|
|
{
|
|
auto newListOrValue = dlang_pop(vm);
|
|
auto insertList = dlang_tolist(vm);
|
|
|
|
if (newListOrValue.type == StackValueType::List)
|
|
{
|
|
auto list = std::get<std::shared_ptr<DlangList>>(newListOrValue.data);
|
|
|
|
for (const auto& val : list->values)
|
|
insertList->values.push_back(val);
|
|
}
|
|
else if (newListOrValue.type == StackValueType::Int ||
|
|
newListOrValue.type == StackValueType::Bool ||
|
|
newListOrValue.type == StackValueType::String)
|
|
insertList->values.push_back(newListOrValue);
|
|
|
|
dlang_push(vm, StackValue(StackValueType::List, insertList));
|
|
}
|
|
|
|
void NativeListRemove(DlangVM* vm)
|
|
{
|
|
auto idx = dlang_tonumber(vm);
|
|
auto list = dlang_tolist(vm);
|
|
|
|
list->values.erase(list->values.begin() + idx);
|
|
|
|
dlang_push(vm, StackValue(StackValueType::List, list));
|
|
}
|
|
|
|
void NativeListConcat(DlangVM* vm)
|
|
{
|
|
std::string seperator = "";
|
|
if (dlang_isstring(vm))
|
|
seperator = dlang_tostring(vm);
|
|
|
|
auto list = dlang_tolist(vm);
|
|
|
|
std::stringstream ss;
|
|
for (const auto& item : list->values)
|
|
{
|
|
switch (item.type)
|
|
{
|
|
case StackValueType::Int:
|
|
ss << std::get<double>(item.data);
|
|
break;
|
|
case StackValueType::Bool:
|
|
ss << std::get<bool>(item.data) ? "True" : "False";
|
|
break;
|
|
case StackValueType::String:
|
|
ss << std::get<std::string>(item.data);
|
|
break;
|
|
}
|
|
|
|
if (!seperator.empty())
|
|
ss << seperator;
|
|
}
|
|
|
|
dlang_pushstring(vm, ss.str().substr(0, ss.str().size() - seperator.size()));
|
|
}
|
|
|
|
inline void openlib_list(DlangVM* vm)
|
|
{
|
|
dlang_newtable(vm);
|
|
|
|
dlang_pushcfunction(vm, NativeListInsert);
|
|
dlang_setfield(vm, "insert");
|
|
|
|
dlang_pushcfunction(vm, NativeListRemove);
|
|
dlang_setfield(vm, "remove");
|
|
|
|
dlang_pushcfunction(vm, NativeListConcat);
|
|
dlang_setfield(vm, "concat");
|
|
|
|
dlang_setglobal(vm, "list");
|
|
}
|
|
|
|
#endif |