Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution credit.lua #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 89 additions & 1 deletion c-gaps/credit.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,95 @@
#include <lua.h>
#include <lauxlib.h>

// implement it here
#include <stdlib.h>


int clear_gaps(lua_State* L)
{
luaL_argcheck(L, lua_istable(L, -1), -1, "Error, table_required\n");

size_t table_len = lua_objlen(L, -1);

if ( table_len == 0)
{
lua_newtable(L);
return 1;
}

const char** in_table = (const char**)malloc(sizeof(char*) * table_len);

// get first string
size_t f_size;
lua_rawgeti(L, 1, 1);
in_table[0] = luaL_checklstring(L, -1, &f_size);
lua_pop(L, 1);

//lua_istable

int i = 2;
for (; i <= table_len; i++)
{
size_t str_size;
lua_rawgeti(L, 1, i);

in_table[i - 1] = luaL_checklstring(L, -1, &str_size);
lua_pop(L, 1);

luaL_argcheck(L, str_size == f_size, -1, "Error, sequences must have the same length\n");
}

// create place for out table
char** out_table = (char**)malloc(sizeof(char*) * table_len);
for (i = 0; i < table_len; i++)
{
out_table[i] = (char*)malloc(sizeof(char) * f_size);
}

int j = 0;
size_t new_size = 0;

// delete only gaps columns
for (; j < f_size; j++)
{
char only_gaps = 1;
for (i = 0; i < table_len; i++)
{
if (in_table[i][j] != '-')
{
only_gaps = 0;
}
}


if (! only_gaps)
{
for (i = 0; i < table_len; i++)
{
out_table[i][new_size] = in_table[i][j];
}
new_size++;
}
}


lua_newtable(L); // create lua table

for (i = 0; i < table_len; i++)
{
lua_pushlstring(L, out_table[i], new_size);
lua_rawseti(L, -2, i + 1);
}

// free memory

for (i = 0; i < table_len; i++)
{
free(out_table[i]);
}
free(in_table);
free(out_table);
return 1; // function returns one argument
}

int luaopen_gaps(lua_State* L) {
// return it here
Expand Down